Notes for string json operations in python: pythonjson
Python methods for json operations include:
json.dumps-- Converts a json object (dictionary) to a string object.
json.loads-- Converts a String object to a json object (dictionary)
If you define a 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 perform operations in json format, for example
print jsonstring1.keys()print jsonstring1['results'][0]['policy']
You can also switch to 360 degrees before performing the operation.
jsonstring1=json.dumps(jsonstring1)jsonstring1=json.loads(jsonstring1)print jsonstring1.keys()print jsonstring1['results'][0]['policy']
But be careful when defining string objects.
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 only adds three quotation marks to the preceding json object to convert it into a string. Therefore, theoretically, you can directly use loads and then follow the json operation.
json.loads(jsonstring2)
But the actual error is reported because the double quotation marks before and after braces are not removed. Many online json formatting tools do not report errors for these double quotation marks, but python will, when defining a json object, double quotation marks are added, but no error is reported because the content without the addition is escaped. Therefore, you cannot fully trust the json format verification tool on the Internet.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.