Home > OS >  Writing a JSON file from dictionary, correcting the output
Writing a JSON file from dictionary, correcting the output

Time:02-21

So I am working on a conversion file that is taking a dictionary and converting it to a JSON file. Current code looks like:

data = {json_object}
json_string = jsonpickle.encode(data)
with open('/Users/machd/Mac/Documents/VISUAL CODE/CSV_to_JSON/JSON FILES/test.json', 'w') as outfile:
     json.dump(json_string, outfile)

But when I go to open that rendered file, it is adding three \ on the front and back of each string.

ps: sorry if I am using the wrong terminology, I am still new to python and don't know the vocabulary that well yet.

CodePudding user response:

Try this

import json
data = {"k": "v"}
with open( 'path_to_file.json', 'w') as f:
   json.dump(data, f)

CodePudding user response:

You don't need to use jsonpickle to encode dict data. The json.dump is a wrapper function that convert data to json format firstly, then write these string data to your file.

The reason why you found \\ exist between each string is that, jsonpickle have took your data to string, after which the quote(") would convert to Escape character when json.dump interact.

Just use the following code to write dict data to json

with open('/Users/machd/Mac/Documents/VISUAL CODE/CSV_to_JSON/JSON FILES/test.json', 'w') as outfile:
     json.dump(data, outfile)
  • Related