How to format json string in Python -
i have number of string json format such '{"key1":{0}, "key2":{1}}'.
after retrieve json string , substitute values. '{"key1":{0}, "key2":{1}}'.format("value1", "value2"). # keyerror: '"key1"
the problem caused bracket {, , should use {{ , }} in string, however, not easy add { the string because bracket may appear in middle part such '{"key1":{0}, "key2":{1}, "{3}":"value3"}'
how can format json string?
don't try manipulate data encoded string. decode json before trying apply formatting.
import json json_data = '{"key1":"{0}","key2":"{1}"}' format_args = ["value1", "value2"] data = json.loads(json_data) formatted_data = {key: value.format(format_args) key, value in data.items()} you can re-encode formatted data json if need be.
Comments
Post a Comment