Coder Perfect

What is the best way to parse data in JSON format?

Problem

In Python, my project is currently getting a JSON message from which I need to extract data. Let’s set it to some simple JSON in a string for the time being:

jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'

So far, I’ve been using a list and then json.dumps to generate JSON requests, but I believe I’ll need to use json.loads to do the inverse. I haven’t had much luck with it, though. Could someone please offer me with a snippet that returns “2” when the input is “two” like the example above?

Asked by ingh.am

Solution #1

Very simple:

import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']  # Or `print(data['two'])` in Python 3

Answered by John Giotta

Solution #2

Your json isn’t always a string. If you obtain a json from a url like this, for example:

j = urllib2.urlopen('http://site.com/data.json')

You must use json.load rather than json.loads:

j_obj = json.load(j)

(It’s easy to overlook: the’s’ stands for’string’)

Answered by jisaacstone

Solution #3

Use json.load to load a URL or a file (). Use json.loads for strings with.json content ().

#! /usr/bin/python

import json
# from pprint import pprint

json_file = 'my_cube.json'
cube = '1'

with open(json_file) as json_data:
    data = json.load(json_data)

# pprint(data)

print "Dimension: ", data['cubes'][cube]['dim']
print "Measures:  ", data['cubes'][cube]['meas']

Answered by Mohammad Shahid Siddiqui

Solution #4

Here’s a small example that might help:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The following is the result of the aforementioned code:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that when using print json.dumps(data, indent=4), you can set the ident option of dump to print it like this:

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

Answered by Venkat

Post is based on https://stackoverflow.com/questions/7771011/how-to-parse-data-in-json-format