Python requests, how to send json request without " " - python

my code looks like
data = {
"undelete_user":'false'
}
data_json = json.dumps(data)
print(data_json)
Output is:
{"undelete_user": "false"}
i need output to be without "" so it can look like
{"undelete_user": false}
otherwise when i send request, i will get "failed to decode JSON" error

import json
data = {
"undelete_user": False
}
data_json = json.dumps(data)
print(data_json)
All you had to do was remove 'false' and put False, because you're considering your false as a string, and it should be a boolean.
I hope it helped!

Related

JSON key and value

I am trying to get the values from objects in the following JSON response:
[
{
"compositionId": "-Mkl92Mii2UF3xzi1q7L",
"compositionName": null,
"mainComposition": true,
"animation": {
"state": "Out1"
}
},
{
"compositionId": "bbbbbb",
"compositionName": null,
"mainComposition": true,
"animation": {
"state": "Out1"
}
}
]
What I would like to get in a loop is all the compositionIds but I don't get the correct output.
I can dump the complete JSON with the following code:
import requests
import json
url = 'http://192.168.1.33/data'
r = requests.get(url)
data = json.loads(r.content.decode())
json_str = json.dumps(data)
resp = json.loads(json_str)
print (resp)
You can simply use the requests module, in fact it does provide a builtin json decoder, that is the .json() function. Done that, you can simply iterate over your json objects with a simple for.
You could do something similar to this:
import requests
url = 'http://192.168.1.33/data'
r = requests.get(url)
my_json_file = r.json()
for json_object in my_json_file:
# Do something with json_object['compoitionId']
pass
Try something like this:
import requests
import json
url = 'http://192.168.1.33/data'
r = requests.get(url)
data = json.loads(r.content.decode())
print([d['compositionId'] for d in data])

Check value in dynamically changing nested JSON

I'm trying to get some JSONs using requests library. These JSONs always have status code 200 and normally look so:
{
"response":{
"count":2,
"items":[
{
"id":1,
"first_name":"Lorem",
"last_name":"Ipsum",
"is_closed":false,
"can_access_closed":true,
"track_code":"c8b0bA"
},
{
"id":2,
"first_name":"Lorem",
"last_name":"Ipsum",
"is_closed":false,
"can_access_closed":true,
"track_code":"0776a72"
}
]
}
}
But can be like:
{
"error":{
"error_code":6,
"error_msg":"Too many requests per second",
"request_params":[
{
"key":"count",
"value":"10"
},
{
"key":"",
"value":""
},
{
"key":"v",
"value":"5.103"
}
]
}
}
So I'm trying to request again JSONs that getting error. My current code:
for i in range(20):
while True:
r = requests.get('https://api.github.com/events') #example
json = r.json()
if 'error_code' in json['error']:
continue
break
And I'm getting KeyError: 'error'.
I also tried something like this:
for i in range(20):
while True:
r = requests.get('https://api.github.com/events') #example
json = r.json()
if 'error_code' in json.get('error'):
continue
break
But got TypeError: argument of type 'NoneType' is not iterable
Since json.get('error') can give you None in case error is not inside json, then it is understandable that you get this error. Why don't you do the following:
if 'error' in json:
# code
Also, you should not do while True requests in case of Too many requests. Sleep or at least do exponential backoff in between your requests.
Check if error exists in json and then check the value for error_code:
if json.get('error') and 'error_code' in json.get('error'):
Alternately,
error_code = json.get('error', {}).get{'error_code')
if error_code:
# take action
Try the following code:
import json #change over here
for i in range(20):
while True:
r = requests.get('https://api.github.com/events') #example
json = json.loads(r)
if 'error_code' in json['error']:
continue
break

Getting a specific value of JSON data

I'm getting a JSON data from RESTCONF HTTPS request, using the following code
https_request = 'https://' + host + '/restconf/data/' + operation
headers = {'Content-type': 'application/yang-data+json', 'Accept': 'application/yang-data+json'}
r = requests.get(https_request, auth=(user, password), headers=headers, verify=False)
print r.json()
The data I got is the following:
{
"Cisco-IOS-XE-segment-routing:ipv4": {
"prefixes": [
{
"ipprefix": "1.1.1.1/32",
"index": {
"range-start": 333,
"range": 1
}
}
]
}
}
Basically, I want to return the field's "range-start" value which is 333. I tried the following but it did not work.
for element in r:
id = element['range-start']
print(id)
Is there anyway to get that value?
From Python Console:
>>> import json
... data = json.loads('{"Cisco-IOS-XE-segment-routing:ipv4": {"prefixes": [{"ipprefix": "1.1.1.1/32", "index": {"range-start": 333, "range": 1}}]}}')
... print(data['Cisco-IOS-XE-segment-routing:ipv4']['prefixes'][0]['index']['range-start'])
333
>>>
You need to start at the beginning of the JSON and work your way to the key you want. To do this you need to start at Cisco-IOS-XE-segment-routing:ipv4.
prefixes = r.json()["Cisco-IOS-XE-segment-routing:ipv4"]["prefixes"]
id = prefixes[0]["index"]["range-start"]
If there are multiple prefixes you can loop over them and access each range-start.
Since you are looping over elements, I would suggest this approach using a helper function:
def get_id(element):
prefixes = r.json()["Cisco-IOS-XE-segment-routing:ipv4"]["prefixes"]
id = prefixes[0]["index"]["range-start"]
return id
Then you can do, as in your question:
for element in r:
id = get_id(element)
print(id)

receive and loop through json data in python

I have a JSON data that I sent to my server using AJAX. The data comes here and I see it.
def add_collection(self):
form = AccountForm.LoginForm(request.form)
if self.request.method == 'GET' :
return render_template('add_collection.html',user=current_user,formLogin = form)
elif self.request.method == 'POST' :
for data in self.request.data :
print "The data is %s" %data
When I print self.request.data I get my JSON like
[{"image":"https://mybucket.s3.amazonaws.com/asma.jpg","Description":"Photo Descriptiong"},
{"image":"https://mybucket.s3.amazonaws.com/NCg3G.png","Description":"Photo Description"}]'
The above is exactly what my JSONfile looks like and what I am expecting. However, I want to break it into the two rows and insert into the database. Please how do i loop through JSON. I have seen similar questions here and many more. However, none works for me. When i tried
for data in self.request.data :
print data['image']
TypeError: string indices must be integers, not str
Please how do i achieve this ?Any help would be appreciated.
Below is my ajax request .
$.ajax({
url: "/user/add_collection",
type: 'POST',
contentType:'application/json',
data: JSON.stringify(arr),
dataType:'json',
success : function(data,status){
console.log("The image upload data returns", data);
console.log("the image upload status is", status);
},
error : function(xhr, ajaxOptions, thrownError){
//$.mobile.loading('hide');
if (xhr.status == 200) {
alert(ajaxOptions);
}
else {
alert(xhr.status);
alert(thrownError);
}
}
});
I am using python running flask framework .
I think you are getting the response as a string (self.request.data).
To treat it as objects, you need to convert it (from string to python representation) first:
elif self.request.method == 'POST' :
parsed_json = json.loads(self.request.data)
for data in parsed_json:
print data['image']
JSON data is received as a string. You need to parse it first.
data = json.loads(self.request.data)

post data using python-requests

I'm trying to post the following data. But I'm getting an error. Can you please take look? Thanks a lot.
I'm posting the same data using Postman. And it works.
def _build_post_data(bike_instance):
"""
data = {
"apikey": "XXX",
"data": {
"created_at": "date_XX",
"Price": "Decimal_XX"
}
}
"""
data = {}
raw_data = serializers.serialize('python', [bike_instance])
actual_data = [d['fields'] for d in raw_data]
data.update(
{
"apikey": XXX,
"data": actual_data[0]
}
)
return data
Posting data
bike = Bike.objects.get(pk=XXX)
data = _build_post_data(bike)
dump_data = json.dumps(data, cls=DjangoJSONEncoder)
requests.post(url, data=dump_data)
error
u'{"error":{"message":"422 Unprocessable Entity","errors":[["The data field is required."],["The apikey field is required."]],"status_code":422}}'
data and apikey already in the dict. then why I'm getting an error? Any idea?
Postman works
With Postman you are sending a multipart/form-data request, with requests you only send JSON (the value of the data field in Postman), and are not including the apikey field.
Use a dictionary with the JSON data as one of the values, and pass that in as the files argument. It probably also works as the data argument (sent as application/x-www-urlencoded):
form_structure = {'apikey': 'XXXX', 'data': dump_data}
requests.post(url, files=form_structure)
# probably works too: requests.post(url, data=form_structure)

Categories

Resources