Array in a json - python

I am creating a python project who are working with an api, the api return an json like this:
"1": "2018-10-13T08:28:38.809469028Z",
"result": [
{
"id":3027531,
"created_at":"2018-10-13T08:20:38.809469028Z",
"date":"2018-10-13T08:19:38Z",
"text":"banana",
}
],
I can get 1, but i can't get text in result, can someone help me?
I tried:
response.json()['result']['text']
response.json()['result'].text
response.json().result[0].text

Try this
response_json = response.json()
response_json["result"][0]["text"]
The value for result is a list of dictionaries. We take the first item in that list, and then we ask for the value of text.
Be aware that this assumes that response_json["result"] has at least one item. If it is empty, you will get an IndexError. You should probably check the length of response_json["result"] before using it. Here is an example of how this could be done:
response_json = response.json()
if response_json["result"]:
response_json["result"][0]["text"]
else:
print("result is empty")

d = {"1": "2018-10-13T08:28:38.809469028Z",
"result": [
{
"id":3027531,
"created_at":"2018-10-13T08:20:38.809469028Z",
"date":"2018-10-13T08:19:38Z",
"text":"banana",
}
]}
d['result'][0]['id'] # 3027531
d['result'][0]['text'] # banana

Related

How to remove the first and last portion of a string in Python?

How can i cut from such a string (json) everything before and including the first [ and everything behind and including the last ] with Python?
{
"Customers": [
{
"cID": "w2-502952",
"soldToId": "34124"
},
...
...
],
"status": {
"success": true,
"message": "Customers: 560",
"ErrorCode": ""
}
}
I want to have at least only
{
"cID" : "w2-502952",
"soldToId" : "34124",
}
...
...
String manipulation is not the way to do this. You should parse your JSON into Python and extract the relevant data using normal data structure access.
obj = json.loads(data)
relevant_data = obj["Customers"]
Addition to #Daniel Rosman answer, if you want all the list from JSON.
result = []
obj = json.loads(data)
for value in obj.values():
if isinstance(value, list):
result.append(*value)
While I agree that Daniel's answer is the absolute best way to go, if you must use string splitting, you can try .find()
string = #however you are loading this json text into a string
start = string.find('[')
end = string.find(']')
customers = string[start:end]
print(customers)
output will be everything between the [ and ] braces.
If you really want to do this via string manipulation (which I don't recommend), you can do it this way:
start = s.find('[') + 1
finish = s.find(']')
inner = s[start : finish]

Accessing Nested Dict from JSON

I'm using requests and JSON to pull some data from an API, and I'm struggling with using a nested dict.
Here is the JSON data:
{"data": [
{
"ContactId": "123",
"EmailAddress": "abc#xyz.com",
"FirstName": null,
"LastName": null,
"ClickDate": "6/6/1966",
"Clicks": "5",
"IPAddress": "1.1.1.1.1",
"UserAgent": "IE8.0",
"UniqueLinksClicked": [
{
"LinkURL": "http://link1.com",
"LinkURL": "http://link2.com",
"LinkURL": "http://link3.com"
}
]
}
]}
I'm able to access all of the ContactID and other 1st level stuff fine, but I can't figure out how to traverse the "LinkURL" stuff.
Here is my python...
result = requests.get(requesturl, headers=headers)
jdata = json.loads(result.content)
for result in jdata["data"]:
contactID = str([(result["ContactId"])])
for result in jdata["data"]["UniqueLinksClicked"]: #I'm doing this wrong, but I'm not sure how.
print(ContactID + " " + str([(result["LinkURL"])]))
The line marked with a comment above generates a TypeError indicating it's a list, where I expected it to be a dict:
list indices must be integers or slices, not str
If instead I drop the ["data"] dereference and try to access "UniqueLinksClicked" on jdata:
for link in jdata["UniqueLinksClicked"]:
I get a key error because the ["UniqueLinksClicked"] is an item inside of the ["data"] dict.
How do I do this correctly?
You can iterate over the links in a nested loop. Do not use the same variable name result in two nested loops! Use a different variable name in the inner loop.
for link in result["UniqueLinksClicked"]:
print(ContactID, link["LinkURL"])
(Moved from question.)
[OP] was confused about the variable naming in the for variable1 in variable2["dict"]: portion. After some help from HÃ¥ken Lid, [they] figured it out.
It should look like this...
for item in jdata["data"]:
contactID = str([(item["ContactId"])])
print(contactID)
for link in item["UniqueLinksClicked"]:
print(link["LinkURL"])

Traversing json array in python

I'm using urllib.request.urlopen to get a JSON response that looks like this:
{
"batchcomplete": "",
"query": {
"pages": {
"76972": {
"pageid": 76972,
"ns": 0,
"title": "Title",
"thumbnail": {
"original": "https://linktofile.com"
}
}
}
}
The relevant code to get the response:
response = urllib.request.urlopen("https://example.com?title="+object.title)
data = response.read()
encoding = response.info().get_content_charset('utf-8')
json_object = json.loads(data.decode(encoding))
I'm trying to retrieve the value of "original", but I'm having a hard time getting there.
I can do print(json_object['query']['pages'] but once I do print(json_object['query']['pages'][0] I run into a KeyError: 0.
How would I be able to, with python retrieve the value of original?
Do this instead:
my_content = json_object['query']['pages']['76972']['thumbnail']['original']
The reason is, you need to mention index as [0] only when you have list as the object. But in your case, every item is of dict type. You need to specify key instead of index
If number is dynamic, you may do:
page_content = json_object['query']['pages']
for content in page_content.values():
my_content = content['thumbnail']['original']
where my_content is the required information.
Doing [0] is looking for that key - which doesn't exist. Assuming you don't always know what the key of the page is, Try this:
pages = json_object['query']['pages']
for key, value in pages.items(): # this is python3
original = value['thumbnail']['original']
Otherwise you can simply grab it by the key if you do know (what appears to be) the pageid:
json_object['query']['pages']['76972']['thumbnail']['original']
You can iterate over keys:
for page_no in json_object['query']['pages']:
page_data = json_object['query']['pages'][page_no]

How to search for specific value in Json array using Python

I'm using a website's API to get information. It outputs 100 values.
What is the best practice of searching for a specific value in this array?
The array looks something like this:
{
"success":true,
"data":
{
"array":
[
{
"id":"1","name":"Value1"
},
{
"id":"2","name":"Value2"
}
]
}
}
I try searching for the data using this snippet I found elsewhere, however it does not work:
for name in (r.json()['data']['array'][0]['name']):
if r.json()['data']['array'][0] == s_name:
ident = r.json()['data']['array'][0]['id']
name = r.json()['data']['array'][0]['name']
print (name + ' - ' + ident)
else:
print ('Nothing was found.')
So if I was trying to reference Value1 how would I do this using Python?
Please note: I'm a rookie developer, first time using Json, not very experienced with Python.
All help is greatly appreciated.
Here is a one-liner example for searching:
aaa = {
"success":True,
"data":
{
"array":
[
{
"id":"1","name":"Value1"
},
{
"id":"2","name":"Value2"
}
]
}
}
[a['name'] for a in aaa['data']['array'] if a['id']=='1']
This will return all the found cases, or an empty array if nothing is found
Not sure where that piece of code came from but it looks very wrong.
Just looking at the structure you can do something like:
for attrs in r.json()['data']['array']:
if attrs['name'] == s_name:
ident = attrs['id']
name = attrs['name']
print(name, '-', ident)
break
else:
print('Nothing found!')
Your code can be simplified a lot:
# no need to call `r.json` so many times, can simply save it to a variable
json_data = r.json()
for item in json_data["data"]["array"]:
if item["name"] == "Value1":
# do something...

How to assert deeply in JSON with python

I am trigerring an API call, and the server response is in JSON format.
the response looks like this:
{
"status": 0,
"not_passed": 1,
"why": [
{
"code": 229,
"reason": "some reason",
}
]
}
I need to assert two thing.
Status and reason
fro status I am using:
r = requests.get_simple(url=Server.MY_SERVER, params=p)
data = json.loads(r.content)
assert data["status"] == 0
but it doesn't work for the 'reason', maybe because the 'reason' is deeper in the nested structure. How can I fix this one?
assert data['why'][0]['reason'] == 'something'
Of course this assumes that data['why'] exists, is a list, and contains a dict as its first element.

Categories