【问题标题】:Python- writing json file as list of dictionariesPython-将json文件写入字典列表
【发布时间】:2017-11-13 08:04:24
【问题描述】:

我正在根据从 url 中提取的信息编写一个 json 文件。如何在单独的行上打印字典的每个元素?

这是我当前的代码:

dct=[{"name": name,
        "cuisine": cuisine,
        "price-range": price,
        "address": address,
        "rating": rating,
        "reviews": score,
        "district": district,
        "url": link
        }]

    with open('openrice_data.json', 'a') as file:
        file.write(json.dumps(dct))

例如,它当前打印如下:

[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]

我希望它像这样打印:

[
{"name": "Chan Kun Kee",
"cuisine": ["Guang Dong", "Dai Pai Dong"],
"price-range": "$51-100",
"address": [22.3884, 114.1958], 
"rating": 3.5,
"reviews": [216, 95, 38],
"district": "Shatin",
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
}
]

【问题讨论】:

    标签: python json


    【解决方案1】:

    更新 实际上,您拥有的是一个字典列表。当您想添加更多元素时,您需要删除字典周围的[]

    要解决您想要使用 indent=0 的特定问题。也可以考虑直接使用json.dump。

    import json
    
    l=[]
    
    dct={"name": 'name',
        "cuisine": 'cuisine',
        "price-range": 'price',
        "address": 'address',
        "rating": 'rating',
        "reviews": 'score',
        "district": 'district',
        "url": 'link'
        }
    
    l.append(dct)
    
    with open('openrice_data.json', 'w') as file:
        json.dump(l,file,indent=0)
    

    输出:

    [
    {
    "name": "name",
    "cuisine": "cuisine",
    "price-range": "price",
    "address": "address",
    "rating": "rating",
    "reviews": "score",
    "district": "district",
    "url": "link"
    }
    ]
    

    继续

    要添加更多元素,您需要这样做:

    # Load json to list
    with open('openrice_data.json') as f:
        l = json.load(f)
    
    # A new dict    
    dct2={"name": 'name',
        "cuisine": 'cuisine',
        "price-range": 'price',
        "address": 'address',
        "rating": 'rating',
        "reviews": 'score',
        "district": 'district',
        "url": 'link'
        }
    
    # Append new dict
    l.append(dct2)
    
    
    with open('openrice_data.json', 'w') as file:
        json.dump(l,file,indent=0)
    

    输出现在包含一个包含 2 个字典的列表。

    [
    {
    "name": "name",
    "cuisine": "cuisine",
    "price-range": "price",
    "address": "address",
    "rating": "rating",
    "reviews": "score",
    "district": "district",
    "url": "link"
    },
    {
    "name": "name",
    "cuisine": "cuisine",
    "price-range": "price",
    "address": "address",
    "rating": "rating",
    "reviews": "score",
    "district": "district",
    "url": "link"
    }
    ]
    

    【讨论】:

    • json.dumps替换json.dump
    • @Loïc 我为什么要这样做? Json.dump 是写入文件的正确命令。
    • 这会将每个值打印在单独的行上,例如,如果餐厅有多种美食,则每种美食都在单独的行上
    • @Greta 你什么意思?这不是你想要的吗?请参阅我的更新答案,因为我认为您使用了错误的结构。
    【解决方案2】:

    不要使用jsonpprint 非常适合这项工作。

    from pprint import pprint
    
    obj = [{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]
    with open('dumpfile.json', 'w+') as f:
        pprint(obj, f)
    

    有一些自定义参数,请查看文档了解更多详细信息: https://docs.python.org/3/library/pprint.html

    【讨论】:

      【解决方案3】:

      使用漂亮的打印机:

      import pprint
      pp = pprint.PrettyPrinter(indent=4)
      pp.pprint(dct)
      

      另外:您当前正在将 dict 放入列表中。 [] 是一个列表 {} 是 python 中的一个字典。 通过放置 [{}] 您将 dict 放入列表中。只需删除 []。

      【讨论】:

      • 抱歉,我没有指定 - 我正在提取餐厅列表的信息,因此每个字典都将包含一家餐厅的信息,所以我希望输出是字典列表。
      【解决方案4】:

      其他人评论过使用pprint,但我想补充一点,pprint 会在您的字典中打印 Python 值的表示形式。它们并不总是与其对应的 JSON 相同,例如:

      >>> from pprint import pprint
      >>> d1 = {"value": None}
      >>> pprint(d1)
      {'value': None}
      

      (这里正确的JSON序列化是{"value": null}

      对于这些类型的值,更好的选择是使用json.dumpjson.dumps。您可以使用indent 参数使其每个元素打印一行。请注意,这也会将每个列表元素打印到它们单独的行中(因此您不会准确地得到每个 JSON 键的一行):

      >>> d2 = [
      ... {"name": "Chan Kun Kee",
      ... "cuisine": ["Guang Dong", "Dai Pai Dong"],
      ... "price-range": "$51-100",
      ... "address": [22.3884, 114.1958], 
      ... "rating": 3.5,
      ... "reviews": [216, 95, 38],
      ... "district": "Shatin",
      ... "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
      ... }
      ... ]
      >>> print(json.dumps(d2, indent=2))
      [
        {
          "name": "Chan Kun Kee",
          "cuisine": [
            "Guang Dong",
            "Dai Pai Dong"
          ],
          "price-range": "$51-100",
          "address": [
            22.3884,
            114.1958
          ],
          "rating": 3.5,
          "reviews": [
            216,
            95,
            38
          ],
          "district": "Shatin",
          "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
        }
      ]
      

      但至少可以保证您始终获得正确的 JSON。此外,您还可以使用自己的 JSON encoder 扩展行为。例如,这允许您将 Python datetime 对象序列化为 JSON 字符串。

      【讨论】:

      • 感谢您的回答!
      猜你喜欢
      • 2018-07-18
      • 1970-01-01
      • 2014-06-30
      • 2020-08-26
      • 2016-03-01
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      相关资源
      最近更新 更多