Home > Software engineering >  Filter Json Keys that contains certain character in Python
Filter Json Keys that contains certain character in Python

Time:05-11

I need to filter all Keys in this dict (book-1, book-2 and book-3) that conatains the string 'book'and save them in a new dict. In this example no need to 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])

CodePudding user response:

This can be accomplished with a dict comprehension, which can be updated based on your needed filter:

new_dict = {key: value for key, value in info['store'].items() if "book" in key}
  • Related