jsonpath_ng支持JSON数据的读写操作。
安装
pip install jsonpath-ng
测试数据
from jsonpath_ng import parse
import json
json_data = '''
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century"
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
'''
data = json.loads(json_data)
查找
matches = parse('$..book[*].category').find(data)
print(matches[0].value)
# reference
新建
matches = parse('$..book[*].price').find_or_create(data)
print(data)
# {'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': {}}
更新
update_or_create
matches = parse('$..book[*].price').update_or_create(data, 100)
print(data)
# 'store': {'book': [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 100}, {'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 100}, {'category': 'fiction', 'author': 'Herman Melville', 'title': 'Moby Dick', 'isbn': '0-553-21311-3', 'price': 100}, {'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 100}], 'bicycle': {'color': 'red', 'price': 19.95}}}
update
matches = parse('$..book[*].price').update(data, 100)
print(data)
# {'store': {'book': [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century'}, {'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 100}, {'category': 'fiction', 'author': 'Herman Melville', 'title': 'Moby Dick', 'isbn': '0-553-21311-3', 'price': 100}, {'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 100}], 'bicycle': {'color': 'red', 'price': 19.95}}}
删除
matches = parse('$..book[*].price').filter(lambda x: x == 12.99, data)
print(data)
# {'store': {'book': [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century'}, {'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 100}, {'category': 'fiction', 'author': 'Herman Melville', 'title': 'Moby Dick', 'isbn': '0-553-21311-3', 'price': 100}, {'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 100}], 'bicycle': {'color': 'red', 'price': 19.95}}}
相关链接
https://github.com/h2non/jsonpath-ng