1
 jsonContent = json.dumps(myDict, default=convert)
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(jsonContent, f, ensure_ascii=False, indent=4)
    return jsonContent

I am doing this to convert a dictionary to json and save it in a file. If I try to print the json with Python, I get an unformatted dict like this:

myDict = {'first': {'phone': 1900, 'desktop': 1577, 'tablet': 148, 'bot': 9, 'other': 1}},

This is still okay. But when I open the file, I see something like this:

"{\"first\": {\"phone\": 1900, \"desktop\": 1577, \"tablet\": 148, \"bot\": 9, \"other\": 1}´}"

How can I remove all the backslashes and format it properly in both, Python and the saved file?

x89
  • 2,798
  • 5
  • 46
  • 110
  • The backslashes are escapes for the double-quote character needed by JSON. – TomServo May 08 '21 at 00:13
  • Can't we print it without them? Or just "prettify" them in either Python printouts or the .json file @TomServo – x89 May 08 '21 at 00:16
  • 2
    Why are you JSON-encoding twice? –  May 08 '21 at 00:27
  • Of course you can prettify them. You can do whatever you like with a string. I mean, as someone else pointed out, you're already encoding it twice. Might as well run a bunch of string replace()s on it. – TomServo May 08 '21 at 00:32
  • 1
    To be clear, you should only encode your data **once**. You're calling `json.dumps()` once on your first line, and `json.dump()` again on your third. Do only one or the other, not both. Right now, you're creating a file that needs to be decoded twice to get your original data out (first to undo the `json.dump()` on the 3rd line, and a second time to undo the `json.dumps()` on the 1st). – Charles Duffy May 08 '21 at 00:44

1 Answers1

0

Write to your json file like this if you want don't want the backslashes

import json
myDict = {"first": {"phone": 1900,"other": 1}, "second": {"adwords": 1419, "no_om_source": 1223}}
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(myDict, f, ensure_ascii=False, indent=4)
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44