0

I want to realize an AWS Lambda function that parse a json message received from IoT.

I receive this json:

{u'Ut': 1488467722, u'Rh': 59.4, u'Id': u'test', u'Temp': 21.6}

How can I parse this string to store each value into a variable?

Thanks

1 Answer 1

3

You have a few options here, one thing that should work quite nicely is to make this a dictionary. You can do this using the inbuilt json module:

import json

orig_json_string = "{u'Ut': 1488467722, u'Rh': 59.4, u'Id': u'test', u'Temp': 21.6}"

json_string = orig_json_string.replace("u'", "\"").replace("'", "\"")
my_dict = json.loads(json_string)

print(my_dict['Ut'])
>>>> 1488467722

Note that the replace("u'", "\"") is only there because the question specifies a string with the unicode identifier included. This is only shown when you output a string so in general you should only use the replace("'", "\"") call.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the reply. If I debug the code with python 2.7 I gave this error: json_string = '{u'Ut': 1488467722, u'Rh': 59.4, u'Id': u'test', u'Temp': 21.6}' ^ SyntaxError: invalid syntax
@Federico I've updated the answer to correct this, you either need to enclose the string in double quotes, or escape each inner single quote (u'Ut' -> u\'Ut\')
I tried before with double quotes but I get this error now: ValueError: Expecting property name: line 1 column 2 (char 1). Thanks
@Federico, it seems that the json library likes the property names in double quotes, I've updated the answer, this version works for me.
Yes, but I need to extract the json fiel from the original string: {u'Ut': 1488467722, u'Rh': 59.4, u'Id': u'test', u'Temp': 21.6}.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.