当前位置: 首页 > 知识库问答 >
问题:

如何将json文件中的“”更改为“”[重复]

赵光赫
2023-03-14

如何将“”更改为“”?我需要使用sqlalchemy中的数据编写database.json

数据是我数据库的名字

all_data = Data.query.all()
data_schema = DataSchema(many=True)
output = data_schema.dump(all_data) 
OutputJson = jsonify({'products':output})

while True:
    with open('database.json',"w") as file:
        file.write(str({'products': output}))
    
    with open('database.json',"r") as files:
        FinalOutput = files.read()

        return FinalOutput

但我的输出是这样的:

{'products': [
    {'id': 0,
     'name': 0,
     'price': 0,
     'quantity': 1
    }
]}

它应该是这样的:

{
  "products": [
    {
      "id": 1,
      "name": "Aspirina",
      "price": 100,
      "quantity": 1
    }
  ]
}

共有1个答案

岳锦
2023-03-14

修改此部分:

with open('database.json',"w") as file:
        file.write(str({'products': output}))

import json
json_data = {}
with open('database.json',"r") as file:
        json_data = json.load(file)
json_data['products'] = output
with open('database.json',"w+") as file:
        json.dump(json_data)
 类似资料: