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.
CodePudding user response:
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"}'
CodePudding user response:
import json
data = {
'H2': 14199,
'Ethanol': 18151,
}
json_str = json.dumps(data)
print(json_str)
Output: {"H2": 14199, "Ethanol": 18151}