python - 如何在 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
}
]
}
解决方案
修改这部分:
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)
推荐阅读
- android - 无法为 [type:Factory,primary_type:'yodgorbek.komilov.musobaqayangiliklari.viewmodel.MainViewModel' 创建实例?
- java - 没有文件 IO 的 AWS 凭证
- java - 如何在 JPA 中持久化与其他实体具有多对多关联的实体?
- javascript - 如何改变 Map 对象 ES6 中给定键的值
- r - 使用 extrafont 或 showtext 库向 R 添加字体(在 Mac 上通过 FontBook)
- python - 从 Python 中的语言环境中去除变体?
- android-studio - cmd:找不到服务:活动#Error:ADB在flutter中以退出代码1退出
- python - BeautifulSoup Python 没有捕获文件中的所有 HTML
- python - 用于仅 FTP 虚拟主机的 Python
- android - Android:如何将 R.string 值从 strings.xml 设置为 Kotlin 中的全局常量?