Python extracts data in JSON format

Foreword:

  • We often use json data, and the json data format is mainly used to interact with different languages
  • For example, if you want to provide data to the java side, you need to convert your data into json format.
  • So whether it is provided to other people in the backend or the data result returned from the API, we need to encapsulate it into json data format or parse json data
  • The data format of json is similar to the dictionary in python, all of which are key:value, and of course value can also be in the format of an array

1. Use of JSON

1. Import json package

import json

2. Commonly used methods

function describe
json.dumps Convert python data into json format and provide it
json.loads Parse json format data into python format

Example:
json.loads()

import json

strDict = '{"city": "广州", "name": "小黑"}'
print(type(strDict)) #<class 'str'>

# 将json格式数据转换为python格式,可以看出将str还原为了dict格式
r = json.loads(strDict) 
print(r,type(r)) # {
    
    'city': '广州', 'name': '小黑'} <class 'dict'>

json.dumps()

import json

listStr = [1, 2, 3, 4]
dictStr = {
    
    "city": "北京", "name": "大猫"}
print(type(listStr)) # <class 'list'>
print(type(dictStr)) #<class 'dict'>

# 将python数据转为json格式,可以看出转换后的数据类型均变为了str
s1 = json.dumps(listStr)
s2 = json.dumps(dictStr,ensure_ascii=False)

print(s1,type(s1)) # [1, 2, 3, 4] <class 'str'>
print(s2,type(s2)) # {
    
    "city": "北京", "name": "大猫"} <class 'str'>

Two, actual combat

1.json.loads()

The data format of json is as follows

{
    "animals": {
        "dog": [
            {
                "name": "Rufus",
                "age":15
            },
            {
                "name": "Marty",
                "age": null
            }
        ]
    }
}

We want to get all dog names in json format:

load_data = json.loads(dump_data)
data = load_data['animals']['dog']
result1 = []
for i in data:
    result1.append(i.["name"])
print(result1)

operation result

['Rufus', 'Marty']

2.jsonpath

How to get the number if you use the jsonpath tool?

load_data = json.loads(dump_data)
jobs=load_data['animals']['dog']
result2 = []
for i in data:
# 从根节点开始,匹配name节点
    result2.append(jsonpath.jsonpath(i,'$..name')[0])
print(result2)

insert image description here

Guess you like

Origin blog.csdn.net/modi88/article/details/130332779