0

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.