简体   繁体   English

如何在Python中格式化JSON字符串

[英]How to format json string in Python

I have a number of string with json format such as '{"key1":{0}, "key2":{1}}' . 我有一些json格式的字符串,例如'{"key1":{0}, "key2":{1}}'

After I retrieve the json string and substitute with values. 之后,我检索json字符串并替换为值。 '{"key1":{0}, "key2":{1}}'.format("value1", "value2") . '{"key1":{0}, "key2":{1}}'.format("value1", "value2") # KeyError: '"key1" KeyError: '"key1"

The problem is caused by the bracket { , and I should use {{ and }} in the string, however, it is not easy to add { to the the string because the bracket may appear in the middle part such as '{"key1":{0}, "key2":{1}, "{3}":"value3"}' 问题是由括号{引起的,我应该在字符串中使用{{}} ,但是,在字符串中添加{并不容易,因为括号可能会出现在中间部分,例如'{"key1":{0}, "key2":{1}, "{3}":"value3"}'

How can I format the json string? 如何格式化json字符串?

If you are building these strings yourself or have control over them, have a different format be sent, or build the value as a dictionary and use json.dumps . 如果您自己构建这些字符串或对其进行控制,可以发送其他格式,或者将该值构建为字典并使用json.dumps

However, if you really need to do this, if it's guaranteed that the substitution values will be in the format {X} , then you can escape the string with this kludge: 但是,如果确实需要执行此操作,并且可以保证替换值的格式为{X} ,则可以使用以下kludge来转义字符串:

import re
s = '{"key1":{0}, "key2":{1}}'
begin = re.compile(r'{(?!\d)')
end = re.compile(r'(?<!\d)}')
escaped = end.sub('}}', begin.sub('{{', s))
print(escaped.format(1, 2))

results in 结果是

{"key1":1, "key2":2}

Note that this is not the best solution. 请注意,这不是最佳解决方案。 Considering you have control of the strings, you should be escaping them in some other way. 考虑到您可以控制字符串,您应该以其他方式转义它们。 Maybe use the % syntax instead of str.format ? 也许使用%语法而不是str.format

Don't try to manipulate the data as an encoded string. 不要尝试将数据作为编码字符串来处理。 Decode the JSON before trying to apply the formatting. 尝试应用格式之前,请解码JSON。

import json

json_data = '{"key1":"{0}","key2":"{1}"}'
format_args = ["value1", "value2"]

data = json.loads(json_data)
formatted_data = {key: value.format(*format_args) for key, value in data.items()}

You can then re-encode the formatted data as JSON if need be. 然后,如果需要,您可以将格式化的数据重新编码为JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM