Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import JSON data into Python [duplicate]

Tags:

python

json

file

Trying to find a simple way to import data from a JSON file into Python. My initial thoughts would be to read the file line by line, but this might imply some additional processing which should already be done in a library.

The ideal solution would look something like:

import json_library

the_data = json_library.load_from_file('my_file.json')

where 'my_file.json' contains a JSON-formatted variable.

like image 553
Juan Carlos Coto Avatar asked Jun 20 '14 17:06

Juan Carlos Coto


People also ask

Can JSON have duplicate keys Python?

json_tricks can check for duplicate keys in maps by setting allow_duplicates to False. These are kind of allowed, but are handled inconsistently between json implementations. In Python, for dict and OrderedDict , duplicate keys are silently overwritten.

Can JSON have duplicate fields?

The short answer: Yes but is not recommended.

Can you convert JSON to Python?

Parse JSON - Convert from JSON to Python If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.


1 Answers

json will do that for you.

import json
data = json.load(open('my_file.json', 'r'))

Content of demo file:

{"hello":"stack overflow"}

Demo:

>>> import json
>>> print(json.load(open('my_file.json','r')))
{u'hello': u'stack overflow'}
like image 110
timgeb Avatar answered Sep 30 '22 07:09

timgeb