This is my response to a get request for some json goodness.
I'm getting this in Python, everything works up to here.
I've been searching for json documentation and reading quite a bit but can't seam to find my answer.
How would I get all the email addresses?
{u'-InFSLzYdyg-OcTosYYs': {u'email': u'hello#gmail.com', u'time': 1360707022892}, u'- InFYJya4K6tZa8YSzme': {u'email': u'me#gmail.com', u'time': 1360708587511}}
What I'd want is a list like so:
email = ['hello#gmail.com', 'me#gmail.com']
Thanks in advance.
Like wRAR said, once you have it as a python dict, it should be as simple as:
[x['email'] for x in l.itervalues()]
Assuming you're converted you JSON string to a python dict (see loads()):
>>> from json import loads
>>> myJSON = loads(somejsonstring)
>>> emails = [a[x]['email'] for x in a]
>>> emails
['hello#gmail.com', 'me#gmail.com']
Or even better, use itervalues() as Luke mentioned.
Just do json.loads and process the resulting dict as usual. There is nothing JSON-specific here.
Related
Studying Python, I am following an excellent Corey Schafer tutorial on Flask, he does this (I have extracted and summarized it for obvious reasons):
from folder_app import app # I did it to follow the structure and that the code is equal to the original
s = Serializer(app.config['SECRET_KEY'], 1800) # key, seconds
token = s.dumps({'user_id': 1}).decode('utf-8')
s = Serializer(app.config['SECRET_KEY'])
user_id = s.loads(token)['user_id'] # This is where I have the doubt
print(user_id)
print(type(s.loads(token)))
The code works, the problem I have is that although as you can see (s.loads (token)) is a dict, I expected to see something like this s.loads ({token ['user_id']}), or s.loads (token ['user_id']) or something like that. That is, it is a dict but it does not seem so. And my doubt goes in the sense if this comes from a greater concept of those they call "pythonic" (which I have not seen so far), or is something that only happens particularly as in this case. Incidentally, https://itsdangerous.palletsprojects.com/en/1.1.x/jws/ this appears: loads (self, s, salt = None, return_header = False) the arguments are in parentheses. I hope it is clear what my doubt is :)
I know this is not answer per say but just to add to my comment. This is an example of how the loads function works on dictionaries with the json module. https://docs.python.org/3/library/json.html#json.loads. What it does is take a json string and return the dictionary type object in Python. Your Serializer is doing something similar. It takes the token string and represents it as an object like dict
The s.dumps I am assuming is similar to json.dumps which gives you the json string representation of python dictionary.
import json
my_dict = json.loads('{"user_id": "Mane", "name": "Joe"}')
my_dict['user_id']
So you could just do json.loads('{"user_id": "Mane", "name": "Joe"}')['user_id'] which is just chaining the operations.
I'm consuming an API that returns a list a of objects in a JSON. But when I get its content with Requests lib, the content is a byte array of objects like this :
b'[{"id":44,"id_string":"a2BPQDsGLfLiwo4r5U4JCY","title":"ED_1803_ITAIPAVA_RJ","description":"ED_1803_ITAIPAVA_RJ","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/44"},{"id":57,"id_string":"a3pb3ALiGuQAHD6XzdHAip","title":"ED_v2018_1801_Taba\xc3\xa7u-SP","description":"ED_v2018_1801_Taba\xc3\xa7u-SP","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/57"},{"id":68,"id_string":"a4Gz2dSwRuyQCsjBwNhf3D","title":"ECS_1804_SONHO REAL-BA","description":"ECS_1804_SONHO REAL-BA","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/68"},{"id":2,"id_string":"a4KjYoy8ieCRNykiYb7nGP","title":"ECS_1708_Vila Esperan\xc3\xa7a-SP","description":"ECS_1708_Vila Esperan\xc3\xa7a-SP","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/2"},{"id":38,"id_string":"a7GQQ7xEu4K6HXWYu9SaSC","title":"ECo_1711_Terra Nossa-UF","description":"ECo_1711_Terra Nossa-UF","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/38"},{"id":78,"id_string":"a7NnnbdhBUSsGoxVWBiGFb","title":"ECoSP_1805_Vila Nova Esperan\xc3\xa7a-SP","description":"ECoSP_1805_Vila Nova Esperan\xc3\xa7a-SP","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/78"}]
How can I make it a normal list of dictionares? I tried iterating through the byte array with for in range() , but all I can return are numbers.
You can do this:
import json
dic = json.loads(Your_input)
I can't comment to answers so I'm writing here.
import json
dic = json.loads(Your_input)
This code works perfectly,
but as #jonrsharpe mentioned in the comment section, you don't need to import anything.
You can use:
page = reg.get("your_url")
page.json()
I have some lines of code in Python and thanks to requests and a post request I want to retrieve some data from a server, it should return a JSON file, but the problem is that the response contains a string starting with /*-secure-, then the structure of the normal JSON file and again at the end of the response, after the JSON I can see again something which doesn't belong to JSON structure: */.
How can I get rid of this stuff which leads the JSON decoder to generate a traceback? Thank you!
You can use the strip() function.
In [1]: x = "/*-secure-{'test': 'yes'}-secure-*/"
In [2]: y = x.strip("/*-secure-")
In [3]: y
Out[3]: "{'test': 'yes'}"
This is ugly and I would personally go with #wpercy's answer, but I've not posted a python answer for a while.
>>> x = "/*-secure-{'test': 'yes'}-secure-*/"
>>> x.split("-secure-")[1]
"{'test': 'yes'}"
Do I dare mention this? (Yes, I do.)
>>> x = "/*-secure-{'test': 'yes'}-secure-*/"
>>> x[10:-10]
"{'test': 'yes'}"
So I'm trying to learn Python here, and would appreciate any help you guys could give me. I've written a bit of code that asks one of my favorite websites for some information, and the api call returns an answer in a dictionary. In this dictionary is a list. In that list is a dictionary. This seems crazy to me, but hell, I'm a newbie.
I'm trying to assign the answers to variables, but always get various error messages depending on how I write my {},[], or (). Regardless, I can't get it to work. How do I read this return? Thanks in advance.
{
"answer":
[{"widgets":16,
"widgets_available":16,
"widgets_missing":7,
"widget_flatprice":"156",
"widget_averages":15,
"widget_cost":125,
"widget_profit":"31",
"widget":"90.59"}],
"result":true
}
Edited because I put in the wrong sample code.
You need to show your code, but the de-facto way of doing this is by using the requests module, like this:
import requests
url = 'http://www.example.com/api/v1/something'
r = requests.get(url)
data = r.json() # converts the returned json into a Python dictionary
for item in data['answer']:
print(item['widgets'])
Assuming that you are not using the requests library (see Burhan's answer), you would use the json module like so:
data = '{"answer":
[{"widgets":16,
"widgets_available":16,
"widgets_missing":7,
"widget_flatprice":"156",
"widget_averages":15,
"widget_cost":125,
"widget_profit":"31",
"widget":"90.59"}],
"result":true}'
import json
data = json.loads(data)
# Now you can use it as you wish
data['answer'] # and so on...
First I will mention that to access a dictionary value you need to use ["key"] and not {}. see here an Python dictionary syntax.
Here is a step by step walkthrough on how to build and access a similar data structure:
First create the main dictionary:
t1 = {"a":0, "b":1}
you can access each element by:
t1["a"] # it'll return a 0
Now lets add the internal list:
t1["a"] = ["x",7,3.14]
and access it using:
t1["a"][2] # it'll return 3.14
Now creating the internal dictionary:
t1["a"][2] = {'w1':7,'w2':8,'w3':9}
And access:
t1["a"][2]['w3'] # it'll return 9
Hope it helped you.
I need some ideas on how to parse a list and print a specific value,Lets say I want to parse dependsontext and then just print the number "249452",please suggest ideas
INPUT:-
dependsontext = [{u'isCurrentPatchSet': True, u'revision': u'ad0beef66e5890cde6f0961ed03d8bc7e3defc63', u'ref': u'refs/changes/52/249452/1', u'id': u'Iad0beef66e5890cde6f0961ed03d8bc7e3defc63', u'number': u'249452'}]
OUTPUT:-
249452
since you used the python tag, it looks like you want
dependsontext[0]['number']
dependsontext is a one-element list of dictionaries, so you can get the first element with [0]
Then you can retrieve a value from that dictionary with a key, like ['number']
Your question is a bit unclear though - it's hard to tell if you're using python data structures or strings. If it's the latter, I'd recommend looking at the simplejson module for json parsing.