One of the most used data serialization technique is JSON format. Python has an in-built module JSON to work with JSON data. It supports all types of primitive data types such as number, string, etc, along with python objects. The data are stored in a structured format in JSON. Sometimes it is required to search a particular data from a large JSON string or a JSON file. There are many ways to search for specific data from JSON data. How JSON data can be searched based on key or value using the python script is shown in this article.
Example-1: Search key in simple JSON data
The following script shows how to search if a particular key exists in a JSON string or not. Here, a variable named customerData is defined to store the JSON data. The value of the key will be taken as input from the user. loads() method of JSON module is used to load JSON data in the variable named customer. Next, ‘in’ operator is used to search the key.
# Import json module
import json
# Define json data
customerData ="""{
"id": "3425678",
"name": "John Micheal",
"email": "john@gmail.com",
"type": "regular",
"address": "4258 Poplar Chase Lane, Boise, Idaho."
}"""
# Input the key value that you want to search
keyVal = input("Enter a key value: \n")
# load the json data
customer = json.loads(customerData)
# Search the key value using 'in' operator
if keyVal in customer:
# Print the success message and the value of the key
print("%s is found in JSON data" %keyVal)
print("The value of", keyVal,"is", customer[keyVal])
else:
# Print the message if the value does not exist
print("%s is not found in JSON data" %keyVal)
Output:
The script is executed two times here. An existing key value is given for the first time and a non-existing key value is given for the second time.
Example-2: Search a particular value in JSON data
The following script shows how to search a particular value in JSON data. applicants variable contains the JSON data where the key is used to store the applicant’s name and value is used to store the applicant is present or absent. The script will search the ‘Absent’ value in the JSON data and print the corresponding name value. for loop is used here iterate the JSON data.
# Import json module
import json
# Define json data
applicants ="""{
"Scott C Aldridge": "Present",
"Joe L Foss": "Present",
"Clyde M Gold": "Present",
"Monique C Doolittle": "Absent",
"David M Volkert": "Present",
"Israel M Oneal": "Present",
"Elizabeth M Groff": "Absent"
}"""
# Initialize a counter
counter = 0
# load the json data
appList = json.loads(applicants)
# iterate json to find the list of absent applicant
for key in appList:
if (appList[key] == 'Absent'):
# Check the counter the print the message
if (counter == 0):
print("The following applicants are absent:")
print(key)
counter = counter + 1
# Print the message if no applicant is absent
if (counter == 0):
print("All applicants are present")
Output:
According to the JSON data from the script, two applicants are absent. This will be the resulting output after running the script:
Example-3: Search value in JSON array data using the custom function
In the following script, a JSON array named jsondata is defined. A particular value of a key will be searched here and if the value exists then the value of another related key will be printed as output. search_price() function is defined here take the value of the name key that will be searched in the JSON data and it will print the value of the corresponding unit_price key.
# Import json module
import json
# Define json variable
jsondata = """[
{
"name":"Pen",
"unit_price":5
},
{
"name":"Eraser",
"unit_price":3
},
{
"name":"Pencil",
"unit_price":10
},
{
"name":"White paper",
"unit_price":15
}
]"""
# load the json data
items = json.loads(jsondata)
# Input the item name that you want to search
item = input("Enter an item name:\n")
# Define a function to search the item
def search_price (name):
for keyval in items:
if name.lower() == keyval['name'].lower():
return keyval['unit_price']
# Check the return value and print message
if (search_price(item) != None):
print("The price is:", search_price(item))
else:
print("Item is not found")
Output:
The script is executed two times in this output. ‘pencil’ is taken as the value of the name key that exists in the JSON data. The unit_price of ‘pencil’ is 10 that is printed. Next, ‘book’ is taken as an input value that doesn’t exist in the JSON data.
Example-4: Search key in nested JSON data
The following script shows steps on searching the value of a particular key in the nested JSON data. Here, a nested JSON variable named nestedData is declared to store nested data. This script will search the brand name of the women watch.
# Import json module
import json
# Define json variable of nested data
nestedData = """{
"watch":{
"men":{
"brand":"Titan",
"price":200
},
"women":{
"brand":"Citizen",
"price":250
},
"kid":{
"brand":"Blancpain",
"price":100
}
}
}"""
# Load the json data
watchlist = json.loads(nestedData)
# Search 'brand' for women
if 'brand' in watchlist['watch']['women']:
print(watchlist['watch']['women']['brand'])
Output:
In the above script, there is only one brand value for women watch which is ‘Citizen’. The following will be the output after running the script.
Example-5: Search entry from a JSON file using filter method and lambda
The following steps show how you can search the entry from a JSON file based on a particular key and values. The content of books.json file is given below.
books.json
{
"isbn": "7799349885",
"name": "Essentials of Vehicle Dynamics",
"author": "Joop P. Pauwelussen"
},
{
"isbn": "7799349885",
"name": "Flow and Combustion in Reciprocating Engines",
"author": "C. Arcoumanis and T. Kamimoto"
},
{
"isbn": "7799349885",
"name": "Automotive Ergonomics Driver Vehicle Interaction",
"author": "Nikolaos Gkikas"
}
]
The following script will search the entry from books.json file, where the value of the author key is Nikolaos Gkikas using lambda and filter() method.
# Import JSON module
import json
# Open the existing JSON file for loading into a variable
with open('books.json') as jsondata:
data = json.load(jsondata)
# Search data based on key and value using filter and list method
print(list(filter(lambda x:x["author"]=="Nikolaos Gkikas",data)))
Output:
The following output will appear after running the script.
Conclusion:
When working with a large amount of JSON data and need to find out the specific information from the data with ease, we have to use efficient ways to do the task. Different ways of searching key and value in JSON data are explained in this article to help python users to perform the process successfully.
from Linux Hint https://ift.tt/2SWKKGj
0 Comments