I've the following json:
{
"slate" : {
"id" : {
"type" : "integer"
},
"name" : {
"type" : "string"
},
"code" : {
"type" : "integer",
"fk" : "banned.id"
}
},
"banned" : {
"id" : {
"type" : "integer"
},
"domain" : {
"type" : "string"
}
}
}
I'd like to figure out the best decoding way to have an easily browsable python object presentation of it.
I tried:
import json
jstr = #### my json code above ####
obj = json.JSONDecoder().decode(jstr)
for o in obj:
for t in o:
print (o)
But I get:
f
s
l
a
t
e
b
a
n
n
e
d
And I don't understand what's the deal. The ideal would be a tree (even a list organized in a tree way) that I could browse somehow like:
for table in myList:
for field in table:
print (field("type"))
print (field("fk"))
Is the Python's built-in JSON API extent wide enough to reach this expectation?
6 Answers 6
You seem to need help iterating over the returned object, as well as decoding the JSON.
import json
#jstr = "... that thing above ..."
# This line only decodes the JSON into a structure in memory:
obj = json.loads(jstr)
# obj, in this case, is a dictionary, a built-in Python type.
# These lines just iterate over that structure.
for ka, va in obj.iteritems():
print ka
for kb, vb in va.iteritems():
print ' ' + kb
for key, string in vb.iteritems():
print ' ' + repr((key, string))
3 Comments
slate_id_type = obj['slate']['id']['type']. Since we assume he's using those values for something, might as well declare them right there. Much better to be explicit anyways.try, except blocks around to catch any possible key value not being present. Check out docs.python.org/3.6/library/exceptions.html (change to 2.7 if you're using that) for more options for exceptions.Try
obj = json.loads(jstr)
instead of
obj = json.JSONDecoder(jstr)
1 Comment
json.loads() returns a Python dictionary from the JSON object.The deal I guess is that you create a decoder, but never tell it to decode().
Use:
o = json.JSONDecoder().decode(jstr)
3 Comments
dict (dictionary) object. By default, iterating over it gets the keys, which are strings. Iterating over a string gets you characters. You can use .iteritems() to get tuples of (key, value), or .itervalues() to get just values in your for loop on the dictionary.The signature of JSONDecoder is
class json.JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[,
parse_constant[, strict[, object_pairs_hook]]]]]]])
and does not accept the JSON string in the constructur. Look at its decode() method.
Comments
This worked well for me, and the printing is simpler than explicitly looping through the object like in Thanatos' answer:
import json
from pprint import pprint
jstr = #### my json code above ####
obj = json.loads(jstr)
pprint(obj)
This uses the "Data Pretty Printer" (pprint) module, the documentation for which can be found here.
Comments
The String you provide in the example is not valid JSON.
The last comma between two closing curly braces is illegal.
Anyway you should follow Sven's suggestion and use loads instead.