Coder Perfect

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


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

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

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

For URL or file, use json.load(). 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": "", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"

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

print json.dumps(data)

The following is the result of the aforementioned code:

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

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": " was present!", 
        "fd_id": "12345", 
        "fc": ""
    "fa": ""

Answered by Venkat

Post is based on