[英]How can I sort json data for dumping?
I am trying to dump JSON data in Python to a file.我正在尝试将 Python 中的 JSON 数据转储到文件中。 I receive the data as an ImmutableMultiDict from a Flask post request.
我从 Flask 发布请求中收到作为ImmutableMultiDict的数据。 It looks as follows: ImmutableMultiDict([('prefix', ''), ('key1', 'value1'), ('key2', 'value2')]) The data should look like this in the file:
它看起来如下: ImmutableMultiDict([('prefix', ''), ('key1', 'value1'), ('key2', 'value2')])文件中的数据应该如下所示:
{ "prefix": [
{"key1": "value1"},
{"key2" : "value2"}
]
}
The prefix as well as all the other data is part of the post request.前缀以及所有其他数据都是发布请求的一部分。 My question now is: How can I json.dump the ImmutableMultiDict so it appears like this in the file?
我现在的问题是:我怎样才能json.dump ImmutableMultiDict 使其在文件中看起来像这样? Right now it looks like this:
现在它看起来像这样:
{
"prefix": "",
"key1": "value1",
"key2": "value2",
}
The reason why I want to do it the other way is because I want to append data later on by appending it to the array with the "prefix" key.我想以另一种方式进行的原因是因为我想稍后通过使用“前缀”键将其附加到数组来获取 append 数据。 Can anyone show me a way to do this properly please?
谁能告诉我正确执行此操作的方法吗?
Thanks.谢谢。
EDIT:编辑:
Ok.行。 I fixed it so it looks the way it should now.
我修复了它,所以它看起来应该是现在的样子。 The Python code:
Python代码:
def write_to_json(file, data, prefix):
with open(file, "a", encoding="utf-8") as f:
json.dump({prefix : list(data)}, f, indent=4)
Result:结果:
{
"prefix": [
"key1",
"key2"
]
}
As you did not mentioned anything about it, I'd recommend to check ImmutableMultiDict#to_dict()
with flat
parameter, see documentation .由于您没有提及任何相关内容,我建议使用
flat
参数检查ImmutableMultiDict#to_dict()
,请参阅文档。
Maybe I am understanding incorrectly, but are you trying to have multiple keys for "prefix"?也许我理解不正确,但你是否试图为“前缀”设置多个键? This is opposing to the definition of JSON and will not work as the keys of a dict (MultiDict) uses something like a set for store their keys.
这与 JSON 的定义相反,并且不会起作用,因为字典(MultiDict)的键使用类似集合的东西来存储它们的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.