过滤 Json 包含 Python 中特定字符的键
Filter Json Keys that contains certain character in Python
我需要过滤此字典(book-1、book-2 和 book-3)中包含字符串“book”的所有键,并将它们保存在新字典中。在这个例子中不需要 seave 'bicycle'.
import json
# some JSON file:
jInfo = '{"store":{"book-1":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"book-2":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"book-3":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.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}}}'
# parse jsonObject:
info = json.loads(jInfo)
# the result is a Python dictionary:
print(info["store"]["book-1"][0])
这可以通过字典理解来完成,它可以根据您需要的过滤器进行更新:
new_dict = {key: value for key, value in info['store'].items() if "book" in key}
我需要过滤此字典(book-1、book-2 和 book-3)中包含字符串“book”的所有键,并将它们保存在新字典中。在这个例子中不需要 seave 'bicycle'.
import json
# some JSON file:
jInfo = '{"store":{"book-1":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"book-2":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"book-3":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.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}}}'
# parse jsonObject:
info = json.loads(jInfo)
# the result is a Python dictionary:
print(info["store"]["book-1"][0])
这可以通过字典理解来完成,它可以根据您需要的过滤器进行更新:
new_dict = {key: value for key, value in info['store'].items() if "book" in key}