代码之家  ›  专栏  ›  技术社区  ›  Dawn17

如何用python编写多个json文件?

  •  0
  • Dawn17  · 技术社区  · 7 年前

    首先,我想问一个典型的JSON文件格式是什么?

    它是一个对象列表,比如: [ {...}, {...} ... ] ?

    第二,我试着存储多个 dict 对一个人 JSON 使用python的文件。

    我有两个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)
    

    当然,我会迭代一个列表 迪克特 存储多个 迪克特 但是我现在这样做是为了测试格式是否正确。结果 .json 文件看起来像

    数据.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"
    }
    

    看起来很奇怪因为没有 , 在两个物体之间。 做这件事的典型方法是什么?

    0 回复  |  直到 7 年前
        1
  •  0
  •   todaynowork    7 年前

    你需要先在列表中创建一个包含所有日期的对象,然后将此列表转储到文件中。

    test_data_list = [test_data, test_data2]
    
    json.dump(test_data_list, json_file)