333

My project is currently receiving a JSON message in python which I need to get bits of information out of. For the purposes of this, let's set it to some simple JSON in a string:

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

So far I've been generating JSON requests using a list and then json.dumps, but to do the opposite of this I think I need to use json.loads. However I haven't had much luck with it. Could anyone provide me a snippet that would return "2" with the input of "two" in the above example?

martineau
  • 112,593
  • 23
  • 157
  • 280
ingh.am
  • 25,104
  • 42
  • 127
  • 177
  • 12
    **Note**: For those that come here with data that uses `'` single-quote string delimiters, you may have accidentally created string representations for Python dictionaries instead. JSON will *always use `"` delimiters*. If so, repair your code that produces that output to use `json.dumps()` instead of `str()` or `repr()`, and head over to [Convert a String representation of a Dictionary to a dictionary?](//stackoverflow.com/q/988228) to figure out how to recover your Python data. Other clues you have a Python literal? Look for `None`, `True` or `False`, JSON would use `null`, `true` & `false`. – Martijn Pieters Nov 22 '18 at 13:25
  • Those who do not have a jsonStr but a list of dictionaries (possibly with `'` single-quote string delimiters), also have a look here: https://stackoverflow.com/questions/41168558/python-how-to-convert-json-file-to-dataframe – questionto42standswithUkraine May 27 '20 at 22:25

4 Answers4

575

Very simple:

import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']  # Or `print(data['two'])` in Python 3
Alex Waygood
  • 4,796
  • 3
  • 14
  • 41
John Giotta
  • 15,842
  • 6
  • 46
  • 78
  • 1
    Also, have a look at [simplejson](http://code.google.com/p/simplejson/) if you need better performance. More recent versions provide optimizations that greatly improve read and writing. – unode Oct 14 '11 at 19:11
  • 3
    I'm actually using simplejson already: `import simplejson as json`. Forgot to mention but thanks :) – ingh.am Oct 15 '11 at 20:22
  • Got it. Was using `.load` method instead of `.loads` – Sunil Kumar Sep 21 '18 at 06:33
97

Sometimes your json is not a string. For example if you are getting a json from a url like this:

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

you will need to use json.load, not json.loads:

j_obj = json.load(j)

(it is easy to forget: the 's' is for 'string')

jisaacstone
  • 4,154
  • 2
  • 24
  • 38
  • 1
    Just to add that you can get the string content by calling j.read() and then use the loads method. Any way in this case the load() method takes care of calling the .read() – rkachach Jan 15 '16 at 06:27
64

For URL or file, use json.load(). For string with .json content, use json.loads().

#! /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']
wjandrea
  • 23,210
  • 7
  • 49
  • 68
Mohammad Shahid Siddiqui
  • 3,374
  • 2
  • 23
  • 12
31

Following is simple example that may help you:

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 output for the above code will be:

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

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

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}
Guy Avraham
  • 3,156
  • 3
  • 36
  • 46
Venkat
  • 347
  • 4
  • 8