简体   繁体   中英

Convert a sensor raw string to json using Python

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.

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"}'
import json

data =  {
            'H2': 14199,
            'Ethanol': 18151,
        }
json_str = json.dumps(data)
print(json_str)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM