LateCoder
LateCoder

Reputation: 2283

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:

"""{"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. The actual json I have is quite a bit more complex, and it would be a pain to escape all the brackets. Is there an easier way to do this?

Upvotes: 0

Views: 470

Answers (2)

Tim Woocker
Tim Woocker

Reputation: 1996

Use the buildin json module:

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

Upvotes: 1

mgilson
mgilson

Reputation: 309929

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 (e.g. dict, list) and then you can convert those objects to JSON using json.dumps.

Upvotes: 0

Related Questions