there's a json obj:
{'key1': 'val1', 'key2': "{"key3": ["val3"]}"}
how to parse json string and json obj in the same json obj
json.load() => AttributeError: 'str' object has no attribute 'read' json.loads() => JSONDecodeError: Expecting ',' delimiter: line 1 column 232 (char 231)
Pretty sure you want to use JSON library as Himanshu suggested.
I think this will answer your questions: https://bogotobogo.com/python/python-json-dumps-loads-file-read-write.php
the json dumps method takes in an object and returns a string:
a = {'foo': 3}
json.dumps(a)
>>> '{"foo": 3}'
the json load method takes in a file-like object, reads the data from that object, and uses that string to create an object:
with open('file.json') as fh:
a = json.load(fh)
For your specific JSON case I think you want it reformatted like so:
import json
j = {'key1': 'val1',
'key2': "{'key3': ['val3']}"
}
print(json.dumps(j))
>>>> {"key1": "val1", "key2": "{'key3': ['val3']}"}
There are four methods in the json libary: load, loads, dumps, dumps. Here is what they do:
Easiest way is to format the dict with multi-line string, then use json.dumps:
d = {'key1': 'val1', 'key2': """{"key3": ["val3"]}"""}
json.dumps(d) # a new json string
json.loads(d["key2"]) # the obj
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.