Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse data in JSON format?

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?

like image 363
ingh.am Avatar asked Oct 14 '11 17:10

ingh.am


People also ask

What is parsing data in JSON?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.

Can we parse a JSON file?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.

How do I decode a JSON file?

You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.

Is JSON easy to parse?

JSON is a data interchange format that is easy to parse and generate. JSON is an extension of the syntax used to describe object data in JavaScript. Yet, it's not restricted to use with JavaScript. It has a text format that uses object and array structures for the portable representation of data.


2 Answers

Very simple:

import json data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}') print data['two']  # Or `print(data['two'])` in Python 3 
like image 192
John Giotta Avatar answered Sep 17 '22 15:09

John Giotta


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

like image 29
jisaacstone Avatar answered Sep 18 '22 15:09

jisaacstone