python read and save json file

A json file is a common data storage file, which is more advanced than txt and more user-friendly than xml .

At the same time, as a file format of a general protocol, json can be easily read by various languages. Therefore, json is very suitable for storing structured data .

The specific introduction and usage specification of json: https://www.json.org/json-en.html


This article will make a small record and summary about python reading json.

1. read json

In general, the json file stores a dict in python.

For example, in "dabao.json" there is the following content:

  1. {
  2. "name": "dabao",
  3. "id":123,
  4. "hobby": {
  5. "sport": "basketball",
  6. "book": "python study"
  7. }
  8. }

If you need to read "dabao.json", the python script can be written like this: read_json.py

  1. import json
  2. f = open('dabao.json', 'r')
  3. content = f.read()
  4. a = json.loads(content)
  5. print(type(a))
  6. print(a)
  7. f.close()

Note that you need to use open to read the file first, and then use json.loads() to convert the read content into a python dictionary .

2. python saves the dictionary as json

directly to the code:

  1. import json
  2. a = {
  3. "name": "dabao",
  4. "id":123,
  5. "hobby": {
  6. "sport": "basketball",
  7. "book": "python study"
  8. }
  9. }
  10. b = json.dumps(a)
  11. f2 = open('new_json.json', 'w')
  12. f2.write(b)
  13. f2.close()

First downgrade the dict to a string via json.dumps() . Then write the string to the json file. It's that simple.

 

Related: python read and save json file