how to capture data from json? - python

I have a text in json format:
'{"Info":{"Result":"OK","ID":8840,"FamilyName":"book","Title":"A950","Model":"A-A","Name":"A 5","Img":"A950-A.png"}}'
how do I capture the "Img" field
I'm trying to print(json.loads(response.text['Info']['Img']))
but I get an error: string indices must be integers

You're json.loads()ing the wrong thing.
At the moment you're trying to index the string as if it were already parsed into Python data structures and then passing the result into json.loads():
print(json.loads(response.text['Info']['Img']))
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Instead, parse the whole response as JSON and then index into it:
print(json.loads(response.text)['Info']['Img'])
# ^^^^^^^^^^^^^^^^^^^^^^^^^

Related

Convert Json format String to Link{"link":"https://i.imgur.com/zfxsqlk.png"}

I try to convert this String to only the link: {"link":"https://i.imgur.com/zfxsqlk.png"}
I'm trying to create a discord bot, which sends random pictures from the API https://some-random-api.ml/img/red_panda.
With imageURL = json.loads(requests.get(redpandaurl).content) I get the json String, but what do I have to do that I only get the Link like this https://i.imgur.com/zfxsqlk.png
Sorry if my question is confusingly written, I'm new to programming and don't really know how to describe this problem.
You can simply do this:
image_url = requests.get(your_api_url).json()["link"]
Directly use requests.json(), no need to load the string with json.loads and other manual stuff.
What you get from json.loads() is a Python dict. You can access values in the dict by specifying their keys.
In your case, there is only one key-value pair in the dict: "link" is the key and "https://i.imgur.com/zfxsqlk.png" is the value. You can get the link and store it in the value by appending ["link"] to your line of code:
imageURL = json.loads(requests.get(redpandaurl).content)["link"]

Extract value from json data using python

After doing an API request I get the json 'data' this has each record in a different set if curly brackets under the results square brackets.
I want to extract the numbers and store/print them separated with a comma.
so requested output
0010041,0010042
I have tried using the below however it comes back with the following error.
TypeError: list indices must be integers or slices, not str
If the results only has one set of brackets it works fine, do I have to convert the multiple results into one so and then extract all the times when 'number' appears?
import json
import sys
#load the data into an element
data={'result': [{'number': '0010041', 'day_of_week': 'monday'}, {'number': '0010042', 'day_of_week': 'tuesday'}]}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
print (resp['result'])
print (resp['result']['number'])
Error message is clear: you are trying to access a list of dicts and you aren't doing it correctly.
Replace your last line with:
for i in resp['result']:
print(i['number'])
Update:
As suggested in comments, you can use list comprehension. So to get your desired result, you can do:
print(",".join([i['number'] for i in resp['result']]))

Get JSON response in Python, but in original JavaScript format

I am putting a JSON response into a variable via requests.json() like this:
response = requests.get(some_url, params=some_params).json()
This however converts JSON's original " to Python's ', true to True, null to None.
This poses a problem when trying to save the response as text and the convert it back to JSON - sure, I can use .replace() for all conversions mentioned above, but even once I do that, I get other funny json decoder errors.
Is there any way in Python to get JSON response and keep original JavaScript format?
json() is the JSON decoder method. You are looking at a Python object, that is why it looks like Python.
Other formats are listed on the same page, starting from Response Content
.text: text - it has no separate link/paragraph, it is right under "Response Content"
.content: binary, as bytes
.json(): decoded JSON, as Python object
.raw: streamed bytes (so you can get parts of content as it comes)
You need .text for getting text, including JSON data.
You can get the raw text of your response with requests.get(some_url, params=some_params).text
It is the json method which converts to a Python friendly format.

TypeError: list indices must be integers or slices, not str while parsing JSON

I am trying to print out at least one key value from the returned Json, as following this basic tutorial
response=None
booking_source = 'sourceBusinessName'
api_request ='http://api.com'
r = requests.get(api_request)
while response is None:
response = r.content.decode('utf-8')
data = json.loads(response)
print (data[booking_source])
return HttpResponse(data[booking_source])
But it returns TypeError: list indices must be integers or slices, not str
probably because I am giving an string instead of an integer to data when printing, but then what I am doing wrong here ?
With requests you can skip the decoding of the response and parsing it as JSON by using the response's json method:
r = requests.get(api_request)
data = r.json()
print data # so you can see what you're dealing with
At this point I suggest dumping out the value of data so that you can see the structure of the JSON data. Probably it is a JSON array (converted to a Python list) and you simply need to take the first element of that array before accessing the dictionary, but it's difficult to tell without seeing the actual data. You might like to add a sample of the data to your question.
Your JSON is an array at the top level, but you're trying to address it as if it were:
{
"sourceBusinessName": {
...
},
...
}

Pass a variable to extract from JSON String in Python?

I have below JSON String. Now I want to extract each individual field from that JSON string.
So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.
Below is my python script -
#!/usr/bin/python
import json
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
def parse_json(data):
jj = json.loads(jsonData)
return jj['+data+']
print parse_json('pp')
Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -
return jj['+data+']
KeyError: '+data+'
Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?
You probably just want this:
return jj[data]
Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.
Just use data parameter itself.
Replace following line:
return jj['+data+'] # lookup with `+data+`, not `pp`
with:
return jj[data]

Categories

Resources