首页 > 解决方案 > 如何在 json 文件中将“”更改为“”

问题描述

如何将 ' ' 更改为 "" ?我需要使用来自 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
    }
  ]
}

标签: pythonjsonflask

解决方案


修改这部分:

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)

推荐阅读