简体   繁体   English

如何格式化python中的JSON

[英]How to format a JSON in python

create a json file the file should be formatted like this:创建一个 json 文件,该文件的格式应如下所示:

 {"name": "YOU", 
    "items": {
    "item 1": "bread", 
        "quantity of item 1": 2, 
        "price of item1": "0.60", 
    "item 2": "milk", 
        "quantity of item 2": 10, 
        "price of item2": "6.00"
    }
}

//I tried to use f.write(

When I tried to create a dictionary and add a the new line operator it would just add \n to the file当我尝试创建字典并添加换行符时,它只会将 \n 添加到文件中

order = {"name": name, "items": {}}
a= 1
for i in items:
    
     order["items"].update({f'item {a}': i.item, +'\n' f'quantity of item {a}': i.quantity,+'\n' f'price of item{a}': i.price()})
     a+=1

Python has the json library for formatting dictionaries into json formats: Python 具有json库,用于将字典格式化为 json 格式:

import json
json_string = json.dumps(items)
print(json_string)

Another issue is that you're defining key-value pairs within a list - you want to use {} instead of [] if you're giving values keys as well, and placing commas in some missed lines:另一个问题是您在列表中定义键值对 - 如果您也提供值键,并且在一些遗漏的行中放置逗号,则您希望使用{}而不是[]

{
    "name": "name",
    "items": {
        "item name": "item1",
        "quantity": 1,
        "price": 1.00
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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