Convert a sensor raw string to json using Python

Viewed 31

Hello i have output data from sensor and im using a python script to send those data using post method but first i need to converts them to json but can't figure it out.

ex. string is

H2 14199        Ethanol 18151

and i want to convert it to

{
    "H2" : "14199",
    "Ethanol" : "18151"
}

so i can POST it in json format.

I tried some code on python but im not that much familiar to it.

1 Answers

Try this:

>>> s = 'H2 14199        Ethanol 18151'
>>> result = dict(map(str.split, s.split('        ')))
>>> result
{'H2': '14199', 'Ethanol': '18151'}

Use the json module to convert the dict to a JSON string:

>>> import json
>>> json.dumps(result)
'{"H2": "14199", "Ethanol": "18151"}'
Related