Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = #### 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?

like image 603
CoolStraw Avatar asked Mar 23 '11 14:03

CoolStraw


1 Answers

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))
like image 117
Thanatos Avatar answered Sep 29 '22 16:09

Thanatos