json模块与jsonpath模块

2018-10-28  本文已影响0人  午夜丶小学徒

一、json模块

# 将python对象转为json对象
jsonData = json.dumps(dictData)
print(jsonData)
print(type(jsonData))
# 将字典(python对象)写入到本地(json对象)
with open('text1.json','w') as f:
    json.dump(dictData,f)
# 将json对象转为python对象
dictData1 = json.loads(jsonData)
print(dictData1)
print(type(dictData1))
# 读取本地的text.json文件 读取到的内容为python对象(字典)
with open('text1.json','rb') as f:
    data = json.load(f)
print(data)
print(type(data))
books = json.load(open("./book.json",'r',encoding='utf-8'))
# print(books)
print(books['store']['book'][0]['price'])
# 查找所有的book的价格
b = books['store']['book']
for i in b:
    print(i['price'])

二、jsonpath模块

- pip install jsonpath
# 1.导包
  import jsonpath
# 2.基本使用
  # 用jsonpath(类比xpath)
  # /html/body/div
  # 在jsonpath中$代表根节点、“.”代表当前节点的子节点,“..”代表当前节点的后代节点
  ret = jsonpath.jsonpath(books,"$.store.book")
  ret = jsonpath.jsonpath(books,"$.store.book[1]")
  ret = jsonpath.jsonpath(books,"$.store.book[*]")
  ret = jsonpath.jsonpath(books,"$.store.book[*].price") # 要取里面的内容 必须加’*‘
  ret = jsonpath.jsonpath(books,"$..author")
  ret = jsonpath.jsonpath(books,"$..book[:3]") # 如果是列表 可以切片
  print(ret)
上一篇下一篇

猜你喜欢

热点阅读