How to find a particular JSON value by key?
My approach to this problem would be different.
As JSON doesn't allow depth first search, so convert the json to a Python Object, feed it to an XML decoder and then extract the Node you are intending to search
from xml.dom.minidom import parseString
import json
def bar(somejson, key):
def val(node):
# Searches for the next Element Node containing Value
e = node.nextSibling
while e and e.nodeType != e.ELEMENT_NODE:
e = e.nextSibling
return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e
else None)
# parse the JSON as XML
foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),)))
# and then search all the name tags which are P1's
# and use the val user function to get the value
return [val(node) for node in foo_dom.getElementsByTagName('name')
if node.firstChild.nodeValue in key]
bar(foo, 'P1')
[u'cccc', u'aaa', u'ss']
bar(foo, ('P1','P2'))
[u'cccc', u'cccc', u'aaa', u'ss']
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'])
Find key by value in python3 json
data = {
"1":
{"name": "Jason"},
"2":
{"name": "Alex"}
}
name = 'Jason'
for key in d:
if (d[key]['name'] == name):
print(key) ## output 1
or in more Pythonic way:
for key, value in data.items():
if name == value['name']:
print(key)
Finding all JSON keys with a certain name in python
Use the following code, if there are only unique items:
def create_db(data, find, other):
db = {}
def recurse(data):
if isinstance(data, list):
for elem in data:
recurse(elem)
elif isinstance(data, dict):
if find in data:
db[data[other]] = data[find]
for k, v in data.items():
recurse(v)
recurse(data)
return db
>>> create_db(data, 'price', 'name')
{'Apple': 3, 'Banana': 2, 'Pear': 4, 'Pineapple': 4, 'cucumber': 3, 'onion': 2}
Else:
def create_db(data, find, other):
db = {}
ctr = {}
def recurse(data):
if isinstance(data, list):
for elem in data:
recurse(elem)
elif isinstance(data, dict):
if find in data:
if data[other] in ctr:
ctr[data[other]] = str(int(ctr[data[other]] or '1') + 1)
else:
ctr[data[other]] = ''
key = data[other] + ctr[data[other]]
db[key] = data[find]
for k, v in data.items():
recurse(v)
recurse(data)
return db
For example, if data
had two Apple
s:
data = {'status': 'success',
'data': {'top_products': {'products': [{'price': 3, 'name': 'Apple'},
{'price': 4, 'name': 'Apple'},
{'price': 2, 'name': 'Banana'}]}}}
# Second approach will add a serial number to each duplicate item
>>> create_db(data, 'price', 'name')
{'Apple': 3, 'Apple2': 4, 'Banana': 2}
For easier access in case of duplicates, you can create a nested dict:
def create_db(data, find, other):
db = {}
def recurse(data):
if isinstance(data, list):
for elem in data:
recurse(elem)
elif isinstance(data, dict):
if find in data:
if data[other] in db:
if isinstance(db[data[other]], dict):
db[data[other]][len(db[data[other]]) + 1] = data[other]
else:
db[data[other]] = {0: db.pop(data[other]), 1: data[find]}
else:
db[data[other]] = data[find]
for k, v in data.items():
recurse(v)
recurse(data)
return db
# For the data in above approach:
>>> create_db(data, 'price', 'name')
{'Apple': {0: 3, 1: 4}, 'Banana': 2}
C# find JSON value based only on Key name through multiple levels of array
You could also use linq and filter the JProperty
collection based on JProperty.Name
. For example
var result = JObject.Parse(jsonString)
.DescendantsAndSelf()
.OfType<JProperty>()
.Single(x=>x.Name.Equals("terminalSize"))
.Value;
How to retrieve an specific value from a JSON involving multiple key value pairs using Javascript array
Ok, so here is a hack. You can use Array
as an Object
and insert any key
you want. You can apply forEach
to it and bind keys
with properties
like below.
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
dictionary.forEach(function(item) { dictionary[item.key] = item;});
console.log(dictionary["History"].value);
Find the value of key from JSON
If you have a grep that can do Perl compatible regular expressions (PCRE):
$ grep -Po '"id": *\K"[^"]*"' infile.json
"4dCYd4W9i6gHQHvd"
-P
enables PCRE-o
retains nothing but the match"id": *
matches"id"
and an arbitrary amount of spaces\K
throws away everything to its left ("variable size positive look-behind")"[^"]*"
matches two quotes and all the non-quotes between them
If your grep can't do that, you an use
$ grep -o '"id": *"[^"]*"' infile.json | grep -o '"[^"]*"$'
"4dCYd4W9i6gHQHvd"
This uses grep twice. The result of the first command is "id": "4dCYd4W9i6gHQHvd"
; the second command removes everything but a pair of quotes and the non-quotes between them, anchored at the end of the string ($
).
But, as pointed out, you shouldn't use grep for this, but a tool that can parse JSON – for example jq:
$ jq '.data.id' infile.json
"4dCYd4W9i6gHQHvd"
This is just a simple filter for the id
key in the data
object. To get rid of the double quotes, you can use the -r
("raw output") option:
$ jq -r '.data.id' infile.json
4dCYd4W9i6gHQHvd
jq can also neatly pretty print your JSON:
$ jq . infile.json
{
"data": {
"name": "test",
"id": "4dCYd4W9i6gHQHvd",
"domains": [
"www.test.domain.com",
"test.domain.com"
],
"serverid": "bbBdbbHF8PajW221",
"ssl": null,
"runtime": "php5.6",
"sysuserid": "4gm4K3lUerbSPfxz",
"datecreated": 1474597357
},
"actionid": "WXVAAHQDCSILMYTV"
}
How to parse json to get all values of a specific key within an array?
You cannot do contents[:]["name"]
since contents
is a list is a dictionary with integer indexes, and you cannot access an element from it using a string name
.
To fix that, you would want to iterate over the list and get the value for key name
for each item
import json
contents = []
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
li = [item.get('name') for item in contents]
print(li)
The output will be
['Bulbasaur', 'Ivysaur']
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)
Related Topics
Matplotlib Axes.Plot() VS Pyplot.Plot()
What's the Best Way to Find the Inverse of Datetime.Isocalendar()
How to Get System Timezone Setting and Pass It to Pytz.Timezone
What Is a '"Python"' Layer in Caffe
Not All Parameters Were Used in the SQL Statement (Python, MySQL)
Numpy.Unique with Order Preserved
How to Transpose Dataframe in Pandas Without Index
Query for List of Attribute Instead of Tuples in SQLalchemy
How to Flatten Lists Without Splitting Strings
Reactornotrestartable Error in While Loop with Scrapy
How to Determine the Length of Lists in a Pandas Dataframe Column
Pandas: Filtering Multiple Conditions
Import a Python Module Without the .Py Extension
Extrapolate Values in Pandas Dataframe
Python Scope: "Unboundlocalerror: Local Variable 'C' Referenced Before Assignment"