-4

Suppose that I have a dictionary dict = {"fadfafa": {"price": 5}} in python. If I do json.dump(dict), then I will end up getting {{"fadfafa":"{\"price\" : 5}"} in the json file. Is there any way to store it in the json file just as how it originally looks like dict = {"fadfafa": {"price": 5}}? So a minimal working example would be:

dict = {"fadfafa": {"price": 5}}
with open('temp.json') as output_file:
     json.dump(dict)

The problem with this output is that when I do

with open('temp.json') as input_file:
     json.load(temp.json = object_pairs_hook = dict_raise_on_duplicates")

It reads back the object not as a dictionary of dictionary but one single dictionary with its value being a string.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Keith
  • 119
  • 5
  • If I understand, you want to store the dictionary in a .json file, right ? – TKirishima Feb 03 '23 at 00:22
  • 3
    Your basic premise is wrong. You won't get `{{` in the JSON file, because that's not valid JSON. The JSON file will look very similar to your original Python dictionary. – Barmar Feb 03 '23 at 00:23
  • 1
    https://stackoverflow.com/questions/17043860/how-to-dump-a-dict-to-a-json-file – TKirishima Feb 03 '23 at 00:25
  • 1
    You'd get something similar to what you show (but just one `{` at the beginning) if the original dictionary were `{"fadfafa": json.dumps({"price" : 5})}` – Barmar Feb 03 '23 at 00:26
  • 3
    Please post a [mre]. – Barmar Feb 03 '23 at 00:27
  • `json.dump(dict)` is missing an argument and `json.load(temp.json =...=...")` is invalid syntax in multiple ways, so this is not an actual example. Make sure to try running your code first and make sure it reproduces the problem. – wjandrea Feb 03 '23 at 00:51

1 Answers1

1

Firstly, don't name your dict 'dict' because that is a reserved word and will cause you problems. Secondly that last bit of code doesn't run so I'm not sure what you want it to do.

But let us see if you assumption is correct:

import json
from io import StringIO
io = StringIO()
    
sample_dict = {"fadfafa":{"price" : 5}}
json.dump(sample_dict, io)
print(io.getvalue())

This gives the output:

{"fadfafa": {"price": 5}}

So the file contents do not have the extra brackets as you state. Let us read it back and compare the result with the original dictionary:

io.seek(0)
new_dict = json.load(io)
print(new_dict)

is_same = all((new_dict.get(k) == v for k, v in sample_dict.items()))
print(is_same)

This gives the output:

{'fadfafa': {'price': 5}}
True

So it seems to behave fine.

RobertB
  • 1,879
  • 10
  • 17