How to Get One Key and Value from a Json in Python

python, How to find specific key value in json file then save whole line of json file?

Bearing in mind that the input file is not a JSON file per se. Each line is valid JSON and therefore has to be dealt with separately.

For example:

import json

with open ('foonew.txt', 'w', encoding='utf-8') as out:
with open('foo.txt', encoding='utf-8') as j:
for line in j:
if (d := json.loads(line))['person']['sex'] == 'male':
print(json.dumps(d), file=out)

The output file will look like:

{"person": {"name": "LANA", "sex": "male", "age": 28}}
{"person": {"name": "KENN", "sex": "male", "age": 26}}

Alternatively, to get a separate file for each gender then:

import json
sexes = []
with open('foo.txt', encoding='utf-8') as j:
for line in j:
d = json.loads(line)
sex = d['person']['sex']
if sex in sexes:
mode = 'a'
else:
sexes.append(sex)
mode = 'w'
with open(f'{sex}.txt', mode, encoding='utf-8') as out:
print(json.dumps(d), file=out)

How to pick specific key & value pairs from JSON [closed]

Save the json output as json file

then

with open("your_file_name.json", "r") as f:#Put Respective File Name
keys = json.load(f)

This will read the file and we made key as a object then you can use that to obtain data , treating json as dict.

Eg of Json Data

{
"sessions": [
{
"address": "Campbellbay",
"available_capacity": 50,
"available_capacity_dose1": 25,
"available_capacity_dose2": 25,
"block_name": "Campbell Bay",
"center_id": 552109,
"date": "19-05-2021",
"district_name": "Nicobar",
"fee": "0",
"fee_type": "Free",
"from": "09:00:00",
"lat": 7,
"long": 93,
"min_age_limit": 45,
"name": "Campbellbay PHC",
"pincode": 744302,
"session_id": "bfea957c-a34e-4b5f-99a0-4c739102eec5",
"slots": [
"09:00AM-11:00AM",
"11:00AM-01:00PM",
"01:00PM-03:00PM",
"03:00PM-05:00PM"
],
"state_name": "Andaman and Nicobar Islands",
"to": "17:00:00",
"vaccine": "COVISHIELD"
},
{
"address": "Car Nicobar",
"available_capacity": 45,
"available_capacity_dose1": 20,
"available_capacity_dose2": 25,
"block_name": "Car Nicobar",
"center_id": 570779,
"date": "19-05-2021",
"district_name": "Nicobar",
"fee": "0",
"fee_type": "Free",
"from": "09:00:00",
"lat": 9,
"long": 92,
"min_age_limit": 45,
"name": "BJR Hospital",
"pincode": 744301,
"session_id": "f7d34d28-d936-4a25-95eb-7a1cdd09c545",
"slots": [
"09:00AM-11:00AM",
"11:00AM-01:00PM",
"01:00PM-03:00PM",
"03:00PM-05:00PM"
],
"state_name": "Andaman and Nicobar Islands",
"to": "17:00:00",
"vaccine": "COVISHIELD"
},
{
"address": "Nancowry",
"available_capacity": 50,
"available_capacity_dose1": 25,
"available_capacity_dose2": 25,
"block_name": "Nancowry",
"center_id": 552108,
"date": "19-05-2021",
"district_name": "Nicobar",
"fee": "0",
"fee_type": "Free",
"from": "09:00:00",
"lat": 7,
"long": 93,
"min_age_limit": 45,
"name": "Nancowry CHC",
"pincode": 744303,
"session_id": "2a73f5c0-d0f8-4272-9cf1-2e68f20d8751",
"slots": [
"09:00AM-11:00AM",
"11:00AM-01:00PM",
"01:00PM-03:00PM",
"03:00PM-05:00PM"
],
"state_name": "Andaman and Nicobar Islands",
"to": "17:00:00",
"vaccine": "COVISHIELD"
}
]
}

So Here If You Want To Get Address

in python

address = keys['sessions']['address']
district = keys['sessions']['district_name']
print(address)
print(district )

Final Code

with open("your_file_name.json", "r") as f:#Put Respective File Name
keys = json.load(f)

address = keys['sessions'][0]['address']
district = keys['sessions'][0]['district_name']
print(address)
print(district )

output

Campbellbay
Nicobar

How to select specific key/value of an object in json via python

You can use list comprehension and dict like this:

device_disco["device"] =[dict(username=k1["username"],password=k1["password"],ip=k1["ip"]) for k1 in 
device_disco["device"]]

jsonData = json.dumps(device_disco)
print (jsonData)

in your code:

import requests
import json

#API request details
url = 'api url'
data = '{"service":"ssh", "user_id":"0", "action":"read_by_user",
"user":"D2", "keyword":"NULL"}'
headers = {"Content-Type": "application/json"}

#Making http request
response = requests.post(url,data=data,headers=headers,verify=False)
print(response)

#Json string
json_disco = response.text
print(type(json_disco))
print(json_disco)

#Decode response.json() method to a python dictionary and use the data
device_disco = response.json()
print(type(device_disco))
print(device_disco)
device_disco["device"] =[dict(username=k1["username"],password=k1["password"],ip=k1["ip"]) for k1 in
device_disco["device"]]

jsonData = json.dumps(device_disco)


with open('devices.json', 'w') as fp:
json.dump(jsonData, fp, indent=4, sort_keys=True)

How to access Value in a JSON string using a Key in Python?

You asked about access a position in a JSON, but the data structure is python dict, with key and values, you can index it only using it's keys as you did well with data['ok'].

To get first key, you can first get the dict.items(), which is a list of the pairs key/value, and then, as it's a list you ca index with ints

data.items()
# [('eee', 'yes'), ('something', None), ('ok', ['no', 'mmm', 'eee']), ('please', False), ('no', {'f': True, 'h': 'ttt'})]


items = list(data.items())
items[0]
# ('eee', 'yes')

How to search JSON object and extract the key/value pair?

Simply when you have the key and you need the value, you have to do this:

>>> dictionary['key']
'value'

In your case:

if item == 'name':
print(item['name'])

Anyway you can simply omitt the if statement this way:

for item in elements:
print(item['name'])

Python: Getting all values of a specific key from json

Below

data = {
"ABC": {
"A": {
"X": "1",
"Y": "2",
"Z": "3",
},
"B": {
"X": "4",
"Y": "5",
"Z": "6",
},
"C": {
"X": "7",
"Y": "8",
"Z": "9",
}
}
}

def get_val(key):
return [entry[key] for entry in data['ABC'].values()]

print(get_val('Y'))

output

['2', '5', '8']

Extract key value pair data from json object, Python

Since your data is a length 1 array, you have to call the 0th index first.

price=data[0]['price']['selling']
store=data[0]['storeNumber']

print(price, store)

The result is as follows:

249.00 289

You can also have the storeNumbers in the availability key which has different values. In this case, you have to specify which value you want to pick but I don't know what you want.



Related Topics



Leave a reply



Submit