Python function to extract specific key value pair from json data.
import json
def extract_key_value(json_data, key):
"""Extracts a specific key-value pair from a JSON data"""
data = json.loads(json_data)
value = data.get(key)
return value
In this example, the function extract_key_value
takes two arguments: json_data
, which is a string containing JSON data, and key
, which is the key for the value that you want to extract.
The function first uses the json.loads
method to convert the json_data
string into a Python dictionary. It then uses the dictionary method get
to retrieve the value associated with the specified key
. If the key
is not found in the dictionary, the method returns None
.
Here’s an example of how you could use this function:
# Example JSON data
json_data = '{"name": "John Doe", "age": 35, "city": "New York"}'
# Extract the value associated with the "age" key
age = extract_key_value(json_data, "age")
# Print the result
print(age) # Output: 35
In this example, the function is called with the json_data
string and the key "age"
. The function returns the value associated with the "age"
key in the JSON data, which is the integer 35
. This value is then assigned to the variable age
and printed to the console.