receive and loop through json data in python - 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)

Related

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

Python requests, how to send json request without " "

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!

converting a JSON string back to an array

I'm passing a 2-dimensional array of float values to my views.py via ajax. My ajax call looks like this:
$.ajax({
method: "POST",
url: "introURL",
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
dsg_mtx : JSON.stringify(dsg_mtx),
},
success: function(data) {
document.getElementById("test").innerHTML = data; // echo response
},
error: function() {
alert ("Something went wrong");
}
I'm pulling my data to the view with this call:
def introURL(request):
if request.is_ajax():
try:
designMtx = json.loads(request.POST['dsg_mtx'], parse_float=None)
except KeyError:
return HttpResponse('Error, intro import')
... Some transformation of designMtx...
return HttpResponse(response)
else:
raise Http404
so my question is how do I convert this json stringify'd object back to a 2-dimensional array which I can use to compute a response? As you can see I tried using the parse_float option, but it's still a str data type.
the array being passed, dsg_mtx, is created with a Handson tables and looks like this:
-1 -1
-1 1
1 -1
1 1
Thanks for your guidance.
My issue turned out to be the default settings for handsontable. while I was supplying the table with float values, by default, the table was converting them to strings. so I was posting a matrix of strings that looked like float. the fix was simply to reformat the handsontable cells where the data was placed.
var data = function () {
return Handsontable.helper.createSpreadsheetData(mtxrows, mtxcols);
};
var hot = new Handsontable(container, {
data: data,
height: 480,
colHeaders: true,
rowHeaders: true,
stretchH: 'none',
columnSorting: true,
contextMenu: true,
className: "htCenter",
cells: function (row, col, prop) {
var cellProperties = {};
if (row > 0) {
cellProperties.type = 'numeric';
cellProperties.format = '0[.]000';
}
return cellProperties;
},
afterChange: function () {
var tmpData = JSON.parse(JSON.stringify(mtx_data));
}
});
So basically anything after the first row is set to numeric type.
so now this line in my ajax call:
dsg_mtx : JSON.stringify(dsg_mtx),
formats it correctly and views.py uses this call to load it in properly:
designMtx = json.loads(request.POST['dsg_mtx'])
Thanks to Tomasz Jakub for suggesting the console.log() which helped me diagnose the issue.
Regards,
Jaime
Try json.loads but in parse_float pass decimal.Decimal
designMtx = json.loads(request.POST['dsg_mtx'], parse_float=decimal.Decimal)

Send Dictionary of Data

Why isn't my json working? Do I need json to send a dictionary of data to my page?
Here is the code in question:
success: function(data) {
var new_data = $.parseJSON(data);
$('td#c00').html(new_data.img);
},
And
results = {'img':img, 'loc':match['number'][p]}
return HttpResponse(json.dumps(results))
I'm trying to send an img url and the number associated with it.
Eventually I want to be able to replace the 'td#c00' tag with one that changes based on the number I pass in through json.
This is how you do it:
var new_data = $.parseJSON(data);
$('td#c00').html(new_data['img']);

django/python reading json?

I'm trying to learn django/python and I'm trying to figure out how to read json data...
I have something like :
{
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
},...
}
I'm trying to read specific data in my html page. Right now this json data is being displayed in the html page.
The source of the this json comes from this:
return HttpResponse(json.dumps(response),mimetype="application/json")
I'm trying to figure out the django/python convention of getting specific data? Am I supposed to do a for each loop? I come from a self taught php background, and I'm trying to teach myself python/django.
Thank you
edit:
I also have this in my view.py before the return HttpResponse
try:
conn = urllib2.urlopen(signed_url, None)
try:
response = json.loads(conn.read())
finally:
conn.close()
except urllib2.HTTPError, error:
response = json.loads(error.read())
This is the easiest way to read json in html (Send by Django)
def sendJson(request):
if request.method == 'GET':
context = {"name":"Json Sample Data"}
return render_to_response('name.html',context)
Django Template Html Code
<div class="col-md-9 center">
<span class="top-text">{{name}}</span>
</div>
Now according to your:
def sendJson(request):
if request.method == 'GET':
jsonData = {
region: {
span: {
latitude_delta: 0.08762885999999526,
longitude_delta: 0.044015180000002374
},
center: {
latitude: 37.760948299999995,
longitude: -122.4174594
}
}
}
data = json.dumps(jsonData)
return HttpResponse(data, content_type="application/json")
you can read this data by using jquery also
another example to create json and read in html
url.py
url(r'^anotherexample/$', 'views.anotherexample', name="anotherexample"),
view.py
def anotherexample(request):
if request.method == 'POST':
_date = strftime("%c")
response_data = {}
response_data['status'] = 'taken'
response_data['issueTakenTime'] = _date
return HttpResponse(json.dumps(response_data), content_type="application/json")
Html view and jquery
$.ajax({
url: "/anotherexample/",
// contentType: "application/json; charset=UTF-8",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", // < here
status : "taken"
},
type: "POST",
error: function(res) {
console.log("errr", res)
},
success: function(res) {
console.log("res", res)}
})
It's not clear what you want to loop over, where, or how, but basic loops work like this:
data = {"key1":[1,2], "key":[4,5]}
for key, values in data.iteritems():
print key, values
I was able to figure out the solution through this link: Decode json and Iterate through items in django template
It helped me and hopefully it'll help someone else who has the same problem as me.
Thanks

Categories

Resources