How to get the second level key's of JSON using python? - python

Below is content of JSON file, how can I get only the keys of the second level, that means I should be able to store the keys like uid,passid,signbuttonid,logoIcon,cornerSettingMenu,logoutButtonId,overlayId,loaderInFunctionalPanel this keys I should be able to store in a list or some array using python. means I need like
list[0]= uid
list[1]=passid
list[2]= signbuttonid
list[3]=logoIcon and so on . . . . . .
{
"GlobalElements" :
[
{
"uid":"userEmail",
"passid":"userPwd",
"signbuttonid": "//button[#class='btn btn-mammoth']",
"logoIcon":"//a[#class='logo text-hide']",
"cornerSettingMenu":"//div[#class='dropdown-toggle']/p",
"logoutButtonId":"//a[#class='logout']",
"overlayId":"//div[#class='overlay']",
"loaderInFunctionalPanel":"//div[#class='small-inline-loader']/child::i[#class='fa
fa-spinner fa-pulse']"
} ]
Note: I don't need values of that. I need only keys.
Can Anybody help me on this. Thanks in advance.

if
import json
a={ "GlobalElements" :[ { "uid":"userEmail", "passid":"userPwd", "signbuttonid": "//button[#class='btn btn-mammoth']", "logoIcon":"//a[#class='logo text-hide']", "cornerSettingMenu":"//div[#class='dropdown-toggle']/p", "logoutButtonId":"//a[#class='logout']", "overlayId":"//div[#class='overlay']", "loaderInFunctionalPanel":"//div[#class='small-inline-loader']/child::i[#class='fa fa-spinner fa-pulse']" } ]}
a= json.dumps(a) #serialize dictionary to json
b=json.loads(a) #unserialize json to get dictionary
get the list of keys with :
l= b["GlobalElements"][0].keys()
print l
[u'uid', u'logoutButtonId', u'logoIcon', u'signbuttonid', u'passid', u'overlayId', u'loaderInFunctionalPanel', u'cornerSettingMenu']

a={ "GlobalElements" :[ { "uid":"userEmail", "passid":"userPwd", "signbuttonid": "//button[#class='btn btn-mammoth']", "logoIcon":"//a[#class='logo text-hide']", "cornerSettingMenu":"//div[#class='dropdown-toggle']/p", "logoutButtonId":"//a[#class='logout']", "overlayId":"//div[#class='overlay']", "loaderInFunctionalPanel":"//div[#class='small-inline-loader']/child::i[#class='fa fa-spinner fa-pulse']" } ]}
l= a["GlobalElements"][0].keys()
print l[0]
print l[1]
print l[2] so on or using for loop worked for me.
Thank you.

First you need to import json
store your json content in a variable. if it is in a file, read the file and store it in variable.
Use dumps() and loads() method to serialize and unserialize and just take the values as below code
import json
x={ "GlobalElements" :[ { "uid":"userEmail", "passid":"userPwd", "signbuttonid": "//button[#class='some id']", "logoIcon":"//a[#class='some id']", "cornerSettingMenu":"//div[#class='dropdown-toggle']/p", "logoutButtonId":"//a[#class='logout']", "overlayId":"//div[#class='overlay']", "loaderInFunctionalPanel":"//div[#class='small-inline-loader']/child::i[#class='fa fa-spinner fa-pulse']" } ] }
x= json.dumps(x)
y=json.loads(y)
z= b["GlobalElements"][0].keys()
here z will be holding the first value of the second level.

Related

How to get a key from inside another key in python

Hey does anybody know how I would go about getting the value of a key which is already inside another key like this:
a = {"fruit":[{"oranges":['10']},{"apples":['11']}]}
print(a.get("fruit"))
I can get the value of "fruit" but how would I get the value of "oranges".
Thank you for any help in advance.
Let's format your dictionary and clearly see what you have:
a = {
"fruit": [
{
"oranges": ['10']
},
{
"apples": ['11']
}
]
}
So, a.get('fruit') gives you a list, which elements can be accessed with indexes.
So a['fruit'][0] gives you
{
"oranges": ['10']
}
and a['fruit'][1] gives you
{
"apples": ['11']
}
So in order to get the value of oranges you should go with:
a['fruit'][0]['oranges']
which will give you: ['10']. ['10'] is a list of its own. If you want to get only the value, you can do:
a['fruit'][0]['oranges'][0]
You just have to access the first element of the list inside fruits, and then access the key inside
print(a['fruit'][0]['oranges']

Removing root node in json in Python

I have a json data stored in a variable.
Json Data:
{ "XYZ": { "abc":[{....}] } }
From above JSON Data, I should not have XYZ node. I need JSON Data as
{ "abc":[{....}] }
How can I remove using Python?
Thanks a lot!
You want to look up the dictionary via it's key ("XYZ") and assign it to a new variable:
data = request_data.get("XYZ")
this will return None if there is no "XYZ" key, but if you know the "XYZ" key is always going to be there you can lookup like so:
data = requests_data["XYZ"]

How to get values from keys from JSON

I'm trying to get some values from a JSON file in Python to create a curl command with these values from the file.
The values that i am looking for are "alarm-id" and "sequence-id".
The JSON file looks like this:
{
"data": [
{
"attributes": {
"alarm-id": "3672400101833445418",
"sequence-id": "1573135238000"
}
}
]
}
I've tried get() but i cant figure out how to use this correctly.
If you need more information just ask.
Thanks in advance!
Best regards
This should work for you
import json
data = json.loads(#yourJSON)
for attribute in data['data']:
print(attribute['attributes']['alarm-id'])
print(attribute['attributes']['sequence-id'])
You have combination of dictionaries and list. Access dictionary key by name dict["key"] and list element by index.
In short, like this:
>>> d = {"data": [{"attributes":{"alarm-id": "3672400101833445418","sequence-id": "1573135238000"}}]}
>>> d["data"][0]["attributes"]["alarm-id"]
'3672400101833445418'

Python - append JSON into main branch

Maybe I am too stuck to see the simple solution for the following problem:
Given:
import json
a = {
"24631331976_defa3bb61f_k.jpg668058":{
"regions": {
"0": {},
"1": {}
}
}
}
b = {
"16335852991_f55de7958d_k.jpg1767935":{
"regions": {
"0": {}
}
}
}
I want to append them in order to get the following output.
enter image description here
Thanks to Daniel Hepper and SegFault, the problem could be solved with:
a.update(b)
c = {}
c.update(a)
c.update(b)
Alternatively, if you are fine with modifying a:
a.update(b)
Note that your code uses Python dictionaries, not JSON strings.
You cannot 'append' a dict to another one, simply because the append add element to the end of an ordered list of elements.
dicts don't have the notion of order, fist or last element. Thus no append for dict.
The action you want to do is merging two dicts, and you can do that using the update method defined for the dict type.
a.update(b)
PS: that will modify the dict a

my loop is only printing the second part of the dictionary , i'm using json

import json
data ='''
{
"names": {"first_boy" : "khaled"},
"names": {"second_boy" : "waseem"}
}
'''
info = json.loads(data)
for line in info:
print(info["names"])
I expected it to print the first_boy and the second_boy dictionary ,but it's printing
{'second_boy': 'waseem'}
Dicts in python can only support one of the same key. Similarly, most implementations of JSON do not allow duplicate keys. The way python handles this, when using json.loads() (or anything else that constructs a dict) is to simply use the most recent definition of any given key.
In this case, {"second_boy":"waseem"} overwrites {"first_boy":"khaled"}.
The problem here is that the key "names" exists 2 times.
Maybe you can do this:
import json
data ='''
{
"names": {"first_boy" : "khaled",
"second_boy" : "waseem"}
}
'''
info = json.loads(data)
for key, value in info['names'].items():
print(key, value)

Categories

Resources