简体   繁体   English

如何在python中格式化json字符串

[英]How to format a json string in python

I have a JSON string (simplified version shown below), and I'd like to be able to format it to dynamically insert values into the "item" field: 我有一个JSON字符串(简化版本如下所示),我希望能够对其进行格式化,以便将值动态插入“项目”字段中:

"""{"a":[{"id":1,"item":{}},{"id":2,"item":{}}]}""".format(8,0)

I get KeyError: '"a"' when I do this, presumably because I need to escape all the other brackets. 这样做时,我得到KeyError: '"a"' ,大概是因为我需要转义所有其他括号。 The actual json I have is quite a bit more complex, and it would be a pain to escape all the brackets. 我拥有的实际json要复杂得多,要摆脱所有括号将很痛苦。 Is there an easier way to do this? 有没有更简单的方法可以做到这一点?

Use the buildin json module: 使用内置的json模块:

import json
data = json.loads(yourjson)
data["a"][0]["item"] = 8
data["a"][1]["item"] = 0
text = json.dumps(dict)

You could use % style formatting: 您可以使用%样式格式:

"""{"a":[{"id":1,"item":%s},{"id":2,"item":%s}]}""" % (8,0)

However, that still feels quite flaky. 但是,这仍然感觉很脆弱。 I think it's probably better to work with python objects (eg dict , list ) and then you can convert those objects to JSON using json.dumps . 我认为使用python对象(例如dictlist )可能更好,然后可以使用json.dumps将这些对象转换为JSON

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

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