python - 在字典中创建字典以将其转换为 Json 数据
问题描述
我的工作流程是,我将在不同的文件中有一些字典,我会将它们调用到一个文件中,比如说 demo.py。我在 demo.py 中有一个变量 temp_dict,其中来自不同文件的字典将被一一附加。例子 ::::
{
"Action": None,
"Parameter": "abc",
"ParameterDescription": "def",
"ExpectedValue": "ghi",
{
"Extensions":"jkl",
"MappedData": "no",
"Parameters": "pqr",
"Labels": "Stu",
}
{
"Recorder": "abc",
"Diagnostics": "efg",
"AdditionalRemarks": ""
}
}
我想要这种类型的结构,我需要在字典中附加字典,我该怎么做。
我还将提供python代码
# function to add data to JSON
def write_json(new_data, filename='report.JSON'):
# new_data is the dictioanries coming from other files, it will be converted into json and dump it into a file.
with open(filename, 'w') as f:
json_string=json.dumps(new_data)
f.write(json_string)
提前致谢
解决方案
您提供的数据不是有效的 python 字典,也不是有效的 JSON。
字典和 JSON 是key: value
对的。该值可能是嵌套字典/JSON,但是在您的示例中,嵌套字典没有键。
但是,这样的事情会起作用:
{
"Action": None,
"Parameter": "abc",
"ParameterDescription": "def",
"ExpectedValue": "ghi",
"YOU NEED SOME NAME HERE": {
"Extensions":"jkl",
"MappedData": "no",
"Parameters": "pqr",
"Labels": "Stu",
},
…
}
您可能一直在考虑数组中的 json 对象/字典。那里的字典不必命名,但那是因为它们隐含了一个名称——它们在有序数组中的索引(位置)
[
{
"name": "Faboor",
"type": "user"
},
{
"name": "prithvi"
"reputation": 19
}
]
推荐阅读
- wordpress - .htacess:在 WordPress 中删除带有异常的查询字符串
- javascript - 如何在本机反应中创建一个更改背景颜色 onPress 的按钮?
- sql - 检查加入是否成功
- c++ - 有没有办法将字符串添加到 Vector 但前提是它不存在?->C++
- java - 在 Android 上显示对话框会禁用窗口焦点,因此 onKeyDown 不会监听触摸事件
- reactjs - ReactJS 中子组件初始数据的引用在哪里
- javascript - Next.js 在按钮上显示/隐藏 div
- javascript - 我需要向我的 Javascript 添加什么才能显示来自我的 DynamoDB 表和 API Gateway 的命中计数器?
- c++ - c++ 条件包含或编译
- android - 在 anr traces.txt 中,'held mutexes=' 是什么意思?