Python json format processing
First, put a piece of code
import requests
import jsonpath
import json
f=open('ip.txt','r',encoding='utf-8')
for my_ip in f.readlines():
my_ip=str(my_ip[:-1])
respons=requests.get('http://ip-api.com/json/{ip}?lang=zh-CN'.format(ip=my_ip)).json()
countr=jsonpath.jsonpath(respons,"$..country")
sheng=jsonpath.jsonpath(respons,"$..regionName")
cit=jsonpath.jsonpath(respons,"$..city")
ipip=jsonpath.jsonpath(respons,"$..query")
print(respons)
print(countr+sheng+cit+ipip)
Json defined
JSON: JavaScript Object Notation(JavaScript 对象表示法)
JSON 是存储和交换文本信息的语法。类似 XML。
JSON 比 XML 更小、更快,更易解析。
1.json moudle use
Python and JSON data type relation table:
Python | JSON | Explanation |
---|---|---|
dict | object | dictionary |
list, tuple | array | sequence |
str | string | String |
int, float | number | Digital Type |
True | true | Boolean value True |
False | false | Boolean value False |
None | null | Null |
Now that you know why you want to convert it to understand how the conversion, which need to use Python's built-in module json, built-in module, can be directly referenced in the code:
import json
json module used on the four main functions:
json.dumps (): the Python data by encoding (converting) data into JSON; json.loads (): the data conversion JSON (decodes) data for Python; The json.dump (): the encoded data and write Python JSON file; json.load (): read data from the file and decoding JSON.
The use 2.jsonpath
JsonPath contrast with XPath syntax:
Json clear structure, high readability, low complexity, very easy to match the corresponding table usage XPath.
Xpath | JSONPath | description |
---|---|---|
/ | $ | With node |
. | @ | The current node |
/ | . or [] | Take the child nodes |
.. | n/a | That is, regardless of location, select all the qualifying conditions |
* | * | Matches all element nodes |
[] | [] | Flag iterator (simple iteration operation can be done on the inside, such as the array index, according to the content selected value, etc.) |
| | [,] | Support iterator do multiple choice |
[] | ?() | Support filtering |
n/a | () | Support for expression evaluation |
() | n/a | Grouping, JsonPath not supported |
Precautions:
json.loads () is converted into a decoded format string Json Python object, if at the time json.loads error codes are decoded to be noted Json characters.
String transcoding
任何平台的任何编码,都能和Unicode互相转换。
UTF-8 and GBK mutual conversion, it is first converted to Unicode UTF-8, and then converting from Unicode to GBK, empathy and vice versa.
# 这是一个 UTF-8 编码的字符串
utf8Str = "你好地球"
# 1. 将 UTF-8 编码的字符串 转换成 Unicode 编码
unicodeStr = utf8Str.decode("UTF-8")
# 2. 再将 Unicode 编码格式字符串 转换成 GBK 编码
gbkData = unicodeStr.encode("GBK")
# 1. 再将 GBK 编码格式字符串 转化成 Unicode
unicodeStr = gbkData.decode("gbk")
# 2. 再将 Unicode 编码格式字符串转换成 UTF-8
utf8Str = unicodeStr.encode("UTF-8")