Getting Values from JSON Using Python

Getting values from JSON using Python

If you want to iterate over both keys and values of the dictionary, do this:

for key, value in data.items():
print(key, value)

How to get value from JSON format

change this:

output = json.loads(response.text)

to this: (using json function you can receive the json response in string format)
load the response into a python dictionary

response_json = json.loads(response.json())

and access the id key from response dictionary

variable = response_json["id"]

Get specific value from json object

To get all the values, you need to iterate on 'attributes' and take each 'value' value

xmp = {
"attributes": [
{"trait_type": "Background","value": "Gray"},
{"trait_type": "Base","value": "Guy"},
{"trait_type": "Body","value": "FormalBlack"},
{"trait_type": "Hand","value": "None"},
{"trait_type": "Head","value": "Astronaut"},
{"trait_type": "Pet","value": "OrangeCat"}
],
}

values = [item['value'] for item in xmp['attributes']]
# ['Gray', 'Guy', 'FormalBlack', ... ]

Getting value from a JSON file based on condition

Assuming your json is a list of the type you put on your question, you can get those values like this:

with open("/Users/metadata.json") as jsonFile:
data = json.load(jsonFile)
for item in data: # Assumes the first level of the json is a list
if ('tags' in item) and ('concept' in item['tags']): # Assumes that not all items have a 'tags' entry
print(item['relativePaths']) # Will trigger an error if relativePaths is not in the dictionary

How can I extract a single value from a nested data structure (such as from parsing JSON)?

For reference, let's see what the original JSON would look like, with pretty formatting:

>>> print(json.dumps(my_json, indent=4))
{
"name": "ns1:timeSeriesResponseType",
"declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
"scope": "javax.xml.bind.JAXBElement$GlobalScope",
"value": {
"queryInfo": {
"creationTime": 1349724919000,
"queryURL": "http://waterservices.usgs.gov/nwis/iv/",
"criteria": {
"locationParam": "[ALL:103232434]",
"variableParam": "[00060, 00065]"
},
"note": [
{
"value": "[ALL:103232434]",
"title": "filter:sites"
},
{
"value": "[mode=LATEST, modifiedSince=null]",
"title": "filter:timeRange"
},
{
"value": "sdas01",
"title": "server"
}
]
}
},
"nil": false,
"globalScope": true,
"typeSubstituted": false
}

That lets us see the structure of the data more clearly.

In the specific case, first we want to look at the corresponding value under the 'value' key in our parsed data. That is another dict; we can access the value of its 'queryInfo' key in the same way, and similarly the 'creationTime' from there.

To get the desired value, we simply put those accesses one after another:

my_json['value']['queryInfo']['creationTime'] # 1349724919000

Getting specific field values from Json Python

You want to print the _id of each element of your json list, so let's do it by simply iterating over the elements:

input_file = open('input_file.txt')
data = json.load(input_file) # get the data list
for element in data: # iterate on each element of the list
# element is a dict
id = element['_id'] # get the id
print(id) # print it

If you want to transform the list of elements into a list of ids for later use, you can use list comprehension:

ids = [ e['_id'] for e in data ]  # get id from each element and create a list of them

Find a value in JSON using Python

You have to iterate over the list of dictionaries and search for the one with the given id_number. Once you find it you can print the rest of its data and break, assuming id_number is unique.

data = [
{
"id_number": "SA4784",
"name": "Mark",
"birthdate": None
},
{
"id_number": "V410Z8",
"name": "Vincent",
"birthdate": "15/02/1989"
},
{
"id_number": "CZ1094",
"name": "Paul",
"birthdate": "27/09/1994"
}
]

for i in data:
if i['id_number'] == 'V410Z8':
print(i['birthdate'])
print(i['name'])
break

If you have control over the data structure, a more efficient way would be to use the id_number as a key (again, assuming id_number is unique):

data =  { "SA4784" : {"name": "Mark", "birthdate": None},
"V410Z8" : { "name": "Vincent", "birthdate": "15/02/1989"},
"CZ1094" : {"name": "Paul", "birthdate": "27/09/1994"}
}

Then all you need to do is try to access it directly:

try:
print(data["V410Z8"]["name"])
except KeyError:
print("ID doesn't exist")
>> "Vincent"

Retrieving key, value of json data python

So, by default a dict will iterate over its keys.

for key in json_data:
print key
# tvs, sofas, etc...

Instead, it seems like you want to iterate over the key-value pairs. This can be done by calling .items() on the dictionary.

 for key, value in json_data.items():
print key, value

Or you can iterate over just the values by calling .values().

How to get key values in a json object(Python)

d.values gives all the values, then you can get the attribute name of each value.

d = {'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}

[i['name'] for i in d.values()]
['poulami', 'test']

Also note that d.values returns a generator and not a list so to convert to list use list(d.values())

Getting values from Json data in Python

If your json data is already a dictionary, then take advantage of that. The beauty of a dictionary / hashmap is that it provides an average time complexity of O(1).

Based on your comment, I believe this will solve your problem:

dfirm_id = []
for feature in cslf['features']:
dfirm_id.append(feature['attributes']['DFIRM_ID'])


Related Topics



Leave a reply



Submit