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'
Related
I am brand new to python and have hit a roadblock I can't seem to figure out.
I have a list of values. This list could have 1 value or many.
['9589503164607', '9589503197375']
I need to output this in a json format. My current output looks like this:
"line_items": {"id": ["9589503164607", "9589503197375"]}
I need this:
{"line_items":[{"id":9589503164607},{"id":9589503197375}]}
Currently, I am using a dictionary for this value and the rest that go with this line. However, due to having duplicate keys ("id"), I feel this may be the wrong approach.
shop_data = {
"fulfillment": {
"location_id": cleanslid,
"tracking_number": trackingnumber,
"line_items": {
"id": iteminvids,
}
}
}
iteminvids is the list I referenced.
If anyone could point me in the right direction I would be so grateful!
Use a list comprehension to create a list of dictionaries.
"line_items": [{"id": item} for item in list_of_values]
If your original list is in lst, you can do
json.dumps({"line_items": [{"id": i} for i in lst}]})
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"]
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.
I have a text file which looks like:
{
"content":
[
{
"id": "myid1",
"path": "/x/y"
},
{
"id": "myid2",
"path": "/a/b"
}
]
}
Is there a way to get the value corresponding to "id" when I pass the
"path" value to my method? For example when I pass /a/b I should get "myid2" in
return. Should I create a dictionary?
Maybe explain briefly what it is you need to actually do as I get a hunch that there might be an easier way to do what you're trying to do.
If i understand the question correctly, if you wanted to find the id by passing a value such as "/x/y" then why not structure the dictionary as
{
"content":
{
"/x/y": "myid1"
},
...(more of the same)
}
This would give you direct access to the value you want as otherwise you need to iterate through arrays.
This looks very much like JSON, so you can use the json module to parse the file. Then, just iterate the dictionaries in the "contents" list and get the one with the matching "path".
import json
with open("data.json") as f:
data = json.load(f)
print(data)
path = "/a/b"
for d in data["content"]:
if d["path"] == path:
print(d["id"])
Output:
{'content': [{'path': '/x/y', 'id': 'myid1'}, {'path': '/a/b', 'id': 'myid2'}]}
myid2
I have a json that looks like this:
[
{
"status":"passed",
"elements":[{"name":"foo"},{"name":"bar"}]
},
{
"status":"failed",
"elements":[{"name":"foo1"},{"name":"bar1"}]
}
]
I am trying to iterate through the elements array:
for a in json['elements']:
print a['name']
I get this error:
TypeError: list indices must be integers, not str
My python is really bad. Thank you
Try this:
for a in json:
for b in a['elements']:
print b['name']
With your code, you are trying to get the value of the key 'elements' from the dictionary json. But json isn't a dict, but an array of dicts. Thus, what you should do instead is:
for dic_x in json:
for dic_y in dic_x['elements']:
print dic_y['name']
You need to loop through your list and then proceed with your data like what you do with dicts like this example:
my_json = [
{
"status":"passed",
"elements":[{"name":"foo"},{"name":"bar"}]
},
{
"status":"failed",
"elements":[{"name":"foo1"},{"name":"bar1"}]
}
]
for element in my_json:
for v in element["elements"]:
print(v["name"])
Output:
foo
bar
foo1
bar1