How to convert python dict to Json file?

Question:

I am having the dict of data which is given below

data = {
    "1": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    "2": [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
}

Now I want this data to be saved into a json file.

Asked By: Proper

||

Answers:

How to convert python dict to json file.

It is very easy in python, you can simply use json module of python to create a json for your data.

Use the code below

import json
data = {
    "1": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
    "2": [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
}

# You can provide path + filename in-place of data.json 
with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

This create a file named data.json in the current working directory.

Answered By: Harsh Narwariya

with open("new_file","w") as f: json.dump(data,f)
json.dumps–is used to write a json to a file

Answered By: python_doomer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.