簡體   English   中英

如何在python中寫入多個json文件?

[英]How to write multiple json files in python?

首先,我想問一下帶有多個對象的JSON文件的典型格式是什么?

它是諸如[ {...}, {...} ... ]的對象列表嗎?

其次,我嘗試使用python將多個dict存儲到單個JSON文件中。

我有兩個JSON:

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'}

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'}

然后我做了

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

當然,我會迭代一個dict列表來存儲多個dict ,但是我現在只是這樣做以測試格式是否正確。 結果.json文件看起來像

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"
}

這似乎很奇怪,因為沒有,兩個物體之間。 這樣做的典型方法是什么?

您需要先創建一個對象,將所有日期保存在列表中。然后將此列表轉儲到文件中。

test_data_list = [test_data, test_data2]

json.dump(test_data_list, json_file)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM