Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of loading JSON from file into a Python dictionary

I am currently doing this to save JSON to a file:

with open(filename, 'w+') as f:
    json.dump(data, f)

and I am doing this to load JSON from a file into a Python dictionary:

with open(filename, 'r') as f:
     data = json.loads(json.load(f))

I understand that json.load loads JSON from a file and json.loads loads JSON from a string.

When I call json.load(f) to load the JSON from file I get a string representation of the JSON object:

'{"a": 1,"b": 2,"c": 3}'

I then call json.loads(json.load(f)) to convert that string representation to a Python dictionary:

{'a': 1, 'b': 2, 'c': 3}

I understand that I can also use ast.literal_eval() to convert the string into a Python dictionary.

My question is - what is the correct way of loading JSON from a file directory into a Python dictionary? is it really necessary to call both json.loads and json.load to get JSON from a file into a dictionary?

like image 416
Teleshot Avatar asked Jun 05 '15 12:06

Teleshot


People also ask

How do you get JSON to load into an ordered dictionary in Python?

To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python. An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted.

How do you read and load a JSON file in Python?

Reading From JSON It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

What is the best way to work with JSON in Python?

Start by importing the json library. We use the function open to read the JSON file and then the method json. load() to parse the JSON string into a Python dictionary called superHeroSquad. That's it!


1 Answers

Your data must have already been a JSON string to begin with and then you double-encoded it during the json.dump. Then of course you need to double-decode it later. So instead of encoding the original JSON with JSON again, just write it to the file as-is:

with open(filename, 'w+') as f:
    f.write(data)
like image 122
Stefan Pochmann Avatar answered Sep 20 '22 01:09

Stefan Pochmann