pookie pookie - 1 year ago 45
JSON Question

How can I access values in this JSON?

I am downloading some JSON from a URL:

from urllib.request import Request, urlopen
import json

url = 'xyz'
r = Request(url, headers={'User-Agent':'Mozilla/5.0'})
weburl = urlopen(r)
dat = weburl.read()
encoding = weburl.info().get_content_charset('utf-8')
j = json.loads(data.decode(encoding))
print(j)


This produces something like:

{
"foo":123,
"bar":4,
"c640103":[5,"xyz", 85.6 ... ],
"c63f456":[8,"pyz", 45.6 ... ],
"c63fdfd":[2,"xhk", 42.8 ... ],
"c64088a":[9,"vyi", 61.1 ... ],
"c63eb0c":[1,"xeq", 25.4 ... ]
}


As can be seen, the keys after
bar
are a bit... odd. I have no idea to know in advance what they are or might be.

How can I get foo as a variable, then get bar as a variable, and then get each of those wonky keys and their array?

I want to get something like this:

foo = j['foo']
bar = j['bar']
wonky_keys = j['wonky_keys']
for i in wonky_keys:
print(i[0]) //5
print(i[1]) //xyz
...

Answer Source

You could run through the json object, when the instance of the value is list than run through the list elements, if it's not list than just print the simple value.

js = {  
   "foo":123,
   "bar":4,
   "c640103":[5,"xyz", 85.6  ],
   "c63f456":[8,"pyz", 45.6  ],
   "c63fdfd":[2,"xhk", 42.8 ],
   "c64088a":[9,"vyi", 61.1],
   "c63eb0c":[1,"xeq", 25.4]
}

for elem in js:
  if isinstance(js[elem], list):
    for elem_li_item in js[elem]:
      print (elem_li_item)
  else:
    print (js[elem])

You can do it with js.items() as well:

for k,v in js.items():
  if isinstance(v, list):
    for elem_li_item in v:
      print (elem_li_item)
  else:
    print (v)

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct, indirect or virtual) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is a tuple of class or type objects (or recursively, other such tuples), return true if object is an instance of any of the classes or types. If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download