I'm trying to parse a JSON object that consists of an array of objects. Each object contains several fields, but fields are often missing. Here's an example:
{
'objects' : [{
'fieldA' : 1,
'fieldB' : 2,
'fieldC' : 3,
},
{
'fieldA' : 7,
'fieldC' : 8,
},
{},
{
'fieldB' : 1,
'fieldC' : 0,
}]
}
I'd like to convert each of the fields into a list, preserving the ordering of the objects, the equivalent of this:
fieldA = [1,7,"Missing","Missing"]
fieldB = [2,"Missing","Missing",1]
fieldC = [3,8,"Missing",0]
Is there a simple way to do this? I can come up with ways to do it that involve a lot of 'if' and 'in' statements and repeated iteration over lists. But it seems like there should be a more pythonic way to do it, something like:
fieldA = [ (obj.fieldA | "missing") for obj in json.objects]
Does python syntax allow something like this?
You need the dict.get()
method:
fieldA = [obj.get("fieldA", "missing") for obj in json["objects"]]
Note that the items of a dictionary are accessed with ["key"]
, not with .key
.
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.