Python: How to Read & Parse JSON

, , …,

the library “json” converts JavaScript JSON format to/from Python nested dictionary/list. Basically, JavaScript array is Python's list, and JavaScript object is Python's dictionary.

Python Object to JSON

Here's example of converting Python object to JSON:

# -*- coding: utf-8 -*-
# python

# python nested dictionary/list to JSON

import json

python_object = ['x3', {'x4': ('8', None, 1.0, 2)}]

print json.dumps(python_object)
# ["x3", {"x4": ["8", null, 1.0, 2]}]

JSON to Python Object

Here's example of converting JSON to Python object:

# -*- coding: utf-8 -*-
# python

# convert JSON to Python nested dictionary/list

import json

json_data = '["x3", {"x4": ["8", null, 1.0, 2]}]'

python_obj = json.loads(json_data)

print python_obj
# [u'x3', {u'x4': [u'8', None, 1.0, 2]}]

Here's example of reading JSON from a file:

# -*- coding: utf-8 -*-
# python

# example of reading JSON from a file

import json
my_data = json.loads(open("xyz.json").read())

print my_data

18.2. json — JSON encoder and decoder — Python v2.7.6 documentation #

Pretty Print JSON

You can use the json lib to pretty print nested hash, by giving the argument indent=1.

# -*- coding: utf-8 -*-
# python

import json  # pretty print nested hash

hh = {3:4,5:6, 7:{9:{8:10},11:12}}

print json.dumps(hh,indent=1)

# {
#  "3": 4,
#  "5": 6,
#  "7": {
#   "9": {
#    "8": 10
#   },
#   "11": 12
#  }
# }
blog comments powered by Disqus