Notes for string type json operations in python
- 2020-06-01 10:05:06
- OfStack
There are methods for python to operate json
json.dumps
-- converts the json object (dictionary) to a string object
json.loads
-- converts a string object to an json object (dictionary)
If you define an json object
jsonstring1={"results":[{"id":"1","name":"\u9ed8\u8ba4\u5206\u7ec4","policy":"4","timer_scan_setting":"{\"last\":\"10.29.13\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"13\"}"},
{"id":"2","name":"\u6d4b\u8bd5\u7684","policy":"1","timer_scan_setting":"{\"last\":\"10.29.15\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"15\"}"},{"id":"4","name":"\u4ea7\u54c1\u7ec4","policy":"3","timer_scan_setting":"{\"last\":\"10.8.15\",\"setting\":\"disable\"}"}]}
You can directly press json, for example
print jsonstring1.keys()
print jsonstring1['results'][0]['policy']
You can turn it 360 degrees
jsonstring1=json.dumps(jsonstring1)
jsonstring1=json.loads(jsonstring1)
print jsonstring1.keys()
print jsonstring1['results'][0]['policy']
But be careful if you define a string object
jsonstring2='''{"results":[{"id":"1","name":"\u9ed8\u8ba4\u5206\u7ec4","policy":"4","timer_scan_setting":"{\"last\":\"10.29.13\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"13\"}"},
{"id":"2","name":"\u6d4b\u8bd5\u7684","policy":"1","timer_scan_setting":"{\"last\":\"10.29.15\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"15\"}"},{"id":"4","name":"\u4ea7\u54c1\u7ec4","policy":"3","timer_scan_setting":"{\"last\":\"10.8.15\",\"setting\":\"disable\"}"}]}'''
This just puts 3 quotes around the json object above to make it a string, so in theory you can just use json after loads
json.loads(jsonstring2)
But the actual error, because big bracket without removing the quotes, online many online json formatting tools for the double quotation marks will not complain, but python, defined json object add double quotation marks when the operation is not an error, because Gary the content will not be escaped, so don't be totally believe online json format calibration tool.
conclusion