Jackson Ming Hu Jackson Ming Hu - 1 month ago 4
JSON Question

How to parse a JSON with an unknown property path?

I've got some JSON strings and I need to parse with Python 3.5. Here is an example of the JSON string:

"termsAndCourses":{
"Semester 2016":{
"000001":{
"courseId":"000001",
"title":"Python",
},
"000035":{
"courseId":"000035",
"title":"Java",
},
"000051":{
"courseId":"000051",
"title":"C#",
}
}


I need to use Python 3.5 to get each course's title, but the property path may be changed and unknown, which means I cannot do it in this way:

result = json.loads(json_str)
print(result["termsAndCourses"]["Semester 2016"]["000001"].title)


In this example above, the two sections of property path "Semester 2016" and "000001" are completely different and irregular from each of the JSON string.

Then how should I get the content from "title" property?

Answer

Did you try to iterate into your JSON object with a for loop?

for semester in result["termsAndCourses"]:
    for course in semester:
        print course

(Not sure about the exact syntax)

Comments