开发者

Python decodes JSON

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 = #### m开发者_如何学运维y 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?


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))


Try

obj = json.loads(jstr)

instead of

obj = json.JSONDecoder(jstr)


The deal I guess is that you create a decoder, but never tell it to decode().

Use:

o = json.JSONDecoder().decode(jstr)


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.

http://docs.python.org/library/json.html#json.JSONDecoder


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜