python处理json

import json


#str----->json
str = '{"name": "御姐", "age": 18}'
j = json.loads(str)
print(j)
print(type(j))

#str----->json------>str
str = '{"name": "御姐", "age": 18}'
j = json.loads(str)
print(j)
j = json.dumps(j)
print(type(j))


#读取字符串 获取里面的内容
with open('file1.txt') as jdata:
    data = json.load(jdata)
    print(data)
    print(data["data"]["Response"]["products"]["prd_1"]["price"])


#读取字符串(json数组格式) 获取里面的内容
with open('file2.txt') as jdata:
    data = json.load(jdata)
    print(data[0])
    print(data[0]["lastName"])


#读取字符串里套json数组
with open('file3.txt') as jdata:
    data = json.load(jdata)
    print(data["data"]["Response"])
    print(data["data"]["Response"][0])
    print(data["data"]["Response"][0]["firstName"])

附录:

file1.txt:

{
	"StoreID": "123",
	"Status": 3,
	"data": {
		"Response": {
			"section": "25",
			"elapsed": 277.141,
			"products": {
				"prd_1": {
					"price": 11.99,
					"qty": 10,
					"upc": "0787493"
				},
				"prd_2": {
					"price": 9.99,
					"qty": 2,
					"upc": "0763776"
				},
				"prd_3": {
					"price": 29.99,
					"qty": 8,
					"upc": "9948755"
				}
			},
			"type": "Tagged"
		}
	}
}

 

file2.txt:

[
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]

 

file3.txt:

{
	"StoreID": "123",
	"Status": 3,
	"data": {
		"Response": [{
				"firstName": "John",
				"lastName": "Doe"
			},
			{
				"firstName": "Anna",
				"lastName": "Smith"
			},
			{
				"firstName": "Peter",
				"lastName": "Jones"
			}
		]
	}
}

 

posted @ 2023-02-16 18:36  万笑佛  阅读(17)  评论(0编辑  收藏  举报