Python Forum

Full Version: Trying to get JSON object in python and process it further
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Am trying to extract a specific field in JSON in python and process it further to send output in e-mail. The problem am facing am able to get the messageId, but nothing else works. Am trying to get userid and phoneno value into variable and use it for further processing, but the output is empty.

But if I try to get messageID, it works, the output is value of messageId
us = data_dict.get('messageId')
print us

Any other key I try to extract doesn't work, any help would be great!

#Display the dictionary in newline
    for key, value in data_dict.items():
       key = key.strip('/').strip('\n')
       value = value.strip('/').strip('\n')
       print(f"KEY:{key}: VALUE:{value}<br>")
   
    us = data_dict.get('userid')
	number = data_dict.get('phoneno')
JSON input looks as below:

Output:
messageId: zZCqqqXvoKx567894QM1 conversationId: XmlgyWS48Qrthuwehs data: {"action":"submit","userid":"xyxr","phoneno":"567894567"},"formMessageId":"LDFWN_ha-fdfdffdeasqwcsd","formId":"user-details-form"}
That looks like improperly formatted json data.
The second dictionary doesn't contain an opening brace.
I guess this is the output from the print and the actual JSON is most likely

Output:
{ "messageId": "zZCqqqXvoKx567894QM1", "conversationId": "XmlgyWS48Qrthuwehs", "data": { "action": "submit", "userid": "xyxr", "phoneno": "567894567" }, "formMessageId": "LDFWN_ha-fdfdffdeasqwcsd", "formId": "user-details-form" }
import json
spam='''{
    "messageId": "zZCqqqXvoKx567894QM1",
    "conversationId": "XmlgyWS48Qrthuwehs",
    "data": {
        "action": "submit",
        "userid": "xyxr",
        "phoneno": "567894567"
    },
    "formMessageId": "LDFWN_ha-fdfdffdeasqwcsd",
    "formId": "user-details-form"
}'''

json_data = json.loads(spam)
print(f"userid: {json_data['data']['userid']}")
print(f"phoneno: {json_data['data']['phoneno']}")
Output:
userid: xyxr phoneno: 567894567