简体   繁体   中英

How to write multiple json files in python?

First of all, I would like to ask what is a typical format of JSON file with multiple objects?

Is it a list of objects like: [ {...}, {...} ... ] ?

Second, I tried to store multiple dict to a single JSON file using python.

I have two JSONs:

test_data = {'profile_img': 'https://fmdataba.com/images/p/4592.png',
 'name': 'Son Heung-Min ',
 'birth_date': '8/7/1992',
 'nation': 'South Korea KOR',
 'position': 'M (R), AM (RL), ST (C)',
 'foot': 'Either'}

and

test_data2 = {'profile_img': 'https://fmdataba.com/images/p/1103.png',
 'name': 'Marc-André ter Stegen ',
 'birth_date': '30/4/1992',
 'nation': 'Germany',
 'position': 'GK',
 'foot': 'Either'}

then I did

with open('data.json', 'w') as json_file:  
    json.dump(test_data, json_file, indent=2)
    json.dump(test_data2, json_file, indent=2)

Of course, I would have iterated a list of dict s to store multiple dict s, but I just did this for now to test if the format is correct. The result .json file looks like

data.json

{
  "profile_img": "https://fmdataba.com/images/p/4592.png",
  "name": "Son Heung-Min ",
  "birth_date": "8/7/1992",
  "nation": "South Korea KOR",
  "position": "M (R), AM (RL), ST (C)",
  "foot": "Either"
}{
  "profile_img": "https://fmdataba.com/images/p/1103.png",
  "name": "Marc-Andr\u00e9 ter Stegen ",
  "birth_date": "30/4/1992",
  "nation": "Germany",
  "position": "GK",
  "foot": "Either"
}

It seems pretty weird because there is not , between two objects. What is the typical way of doing this?

You need create an object hold all your date in list first.Then dump this list to file.

test_data_list = [test_data, test_data2]

json.dump(test_data_list, json_file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM