How access JSON object serialized by Django
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I'm not able to access primary key of an object serialized by Django in JSON. My JavaScript looks like:
function makeLink() {
recorder && recorder.exportWAV(function (blob) {
let fd = new FormData;
fd.append("audio", blob);
let csrftoken = getCookie('csrftoken');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
/*console.log(obj[0].pk);*/
document.getElementById("result").innerHTML = obj.data[0]['pk'];
}
}
xhr.open('POST', uploadAudio_url , true)
//alert(uploadAudio_url)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function () {
// __log("Audio Uploaded to server succesfully");
};
xhr.onerror = function (e) {
// __log("Error Uploading audio" + e)
};
xhr.send(fd);
});
}
I send the blob data which it is an audio file in order to process speech in the backend. The backend process the audio file and filter the objects properly. Then it response to the client with a queryset in JSON. I have interested in get the objects PK and show images in a gallery grid.
This is my
Views.py:
def process_speech(recognized_audio):
speech = recognized_audio
url = '' # Is the URL where the user will be redirected once speech is proccessed
keylist =
for key in Keyword.objects.all():
if(speech.find(key.keyword.lower()) != -1):
keylist.append(key.keyword)
print('Identificado Keyword: ', keylist)
if (speech.find('fotos') != -1 or speech.find('fotografías') != -1):
print("Reconocido FOTO")
imagenes_filtered = Imagen.objects.filter(keyword__keyword__in=keylist)
#print(imagenes_filtered)
return imagenes_filtered
if (speech.find('video') != -1):
print("Reconocido VIDEO")
def upload(request):
print("Método: ", request.method)
print("Ajax: ", request.is_ajax())
if request.method == 'POST':
if request.FILES.get('audio'):
record_audio = request.FILES['audio']
fs = FileSystemStorage()
filename = fs.save(record_audio.name + ".wav", record_audio)
uploaded_file_url = fs.url(filename)
print("File received succesfully")
speech = decodeSpeech(filename)
print(speech)
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(JsonResponse({'data': data}, safe=False),)
else:
return render_to_response('index.html', {"errors":"No recognized audio"})
else:
return HttpResponseRedirect('/home/')
The Json data i get is as follow:
[
{
"model": "Galeria.imagen",
"pk": 20,
"fields":
{"image_width": 6000,
"image_height": 4000,
"fichero_imagen": "files/img/lucas-albuquerque-615558-unsplash.jpg",
"keyword": [17, 18]}
},
{
"model": "Galeria.imagen",
"pk": 21,
"fields":
{"image_width": 5855,
"image_height": 3860,
"fichero_imagen": "files/img/freestocks-org-794156-unsplash.jpg",
"keyword": [18]}
}
]
I have tried things like:
- obj.data[0].pk
- obj.data[0][pk]
- obj.data[0].['pk']
- obj.data.pk[0]
and so on, but I always get undefined.
Thanks in advance
javascript arrays json ajax django
|
show 5 more comments
I'm not able to access primary key of an object serialized by Django in JSON. My JavaScript looks like:
function makeLink() {
recorder && recorder.exportWAV(function (blob) {
let fd = new FormData;
fd.append("audio", blob);
let csrftoken = getCookie('csrftoken');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
/*console.log(obj[0].pk);*/
document.getElementById("result").innerHTML = obj.data[0]['pk'];
}
}
xhr.open('POST', uploadAudio_url , true)
//alert(uploadAudio_url)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function () {
// __log("Audio Uploaded to server succesfully");
};
xhr.onerror = function (e) {
// __log("Error Uploading audio" + e)
};
xhr.send(fd);
});
}
I send the blob data which it is an audio file in order to process speech in the backend. The backend process the audio file and filter the objects properly. Then it response to the client with a queryset in JSON. I have interested in get the objects PK and show images in a gallery grid.
This is my
Views.py:
def process_speech(recognized_audio):
speech = recognized_audio
url = '' # Is the URL where the user will be redirected once speech is proccessed
keylist =
for key in Keyword.objects.all():
if(speech.find(key.keyword.lower()) != -1):
keylist.append(key.keyword)
print('Identificado Keyword: ', keylist)
if (speech.find('fotos') != -1 or speech.find('fotografías') != -1):
print("Reconocido FOTO")
imagenes_filtered = Imagen.objects.filter(keyword__keyword__in=keylist)
#print(imagenes_filtered)
return imagenes_filtered
if (speech.find('video') != -1):
print("Reconocido VIDEO")
def upload(request):
print("Método: ", request.method)
print("Ajax: ", request.is_ajax())
if request.method == 'POST':
if request.FILES.get('audio'):
record_audio = request.FILES['audio']
fs = FileSystemStorage()
filename = fs.save(record_audio.name + ".wav", record_audio)
uploaded_file_url = fs.url(filename)
print("File received succesfully")
speech = decodeSpeech(filename)
print(speech)
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(JsonResponse({'data': data}, safe=False),)
else:
return render_to_response('index.html', {"errors":"No recognized audio"})
else:
return HttpResponseRedirect('/home/')
The Json data i get is as follow:
[
{
"model": "Galeria.imagen",
"pk": 20,
"fields":
{"image_width": 6000,
"image_height": 4000,
"fichero_imagen": "files/img/lucas-albuquerque-615558-unsplash.jpg",
"keyword": [17, 18]}
},
{
"model": "Galeria.imagen",
"pk": 21,
"fields":
{"image_width": 5855,
"image_height": 3860,
"fichero_imagen": "files/img/freestocks-org-794156-unsplash.jpg",
"keyword": [18]}
}
]
I have tried things like:
- obj.data[0].pk
- obj.data[0][pk]
- obj.data[0].['pk']
- obj.data.pk[0]
and so on, but I always get undefined.
Thanks in advance
javascript arrays json ajax django
Is that really the JSON? There are inconsistencies
– Randy Casburn
Nov 25 '18 at 3:45
Well, I generate it according to Django Docs about how to serialize objects so the JSON is generated by Django. Why it is wrong? Im new with JSON.
– Antonio Maestre
Nov 25 '18 at 3:52
I'm not saying it is wrong, I'm saying that you show the root of your JSON data as an array ([
), yet you access the parsed JSON asobj.data
. So what does the complete JSON string look like? So in the commented out console log, what do you get if youconsole.log()
onlyobj
?
– Randy Casburn
Nov 25 '18 at 4:23
tryobj.data[0]['pk']
no dot. Maybeobj.data[0][0]['pk']
– Red Cricket
Nov 25 '18 at 4:37
Oh and it is not json is a python list of dictionaries.
– Red Cricket
Nov 25 '18 at 5:02
|
show 5 more comments
I'm not able to access primary key of an object serialized by Django in JSON. My JavaScript looks like:
function makeLink() {
recorder && recorder.exportWAV(function (blob) {
let fd = new FormData;
fd.append("audio", blob);
let csrftoken = getCookie('csrftoken');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
/*console.log(obj[0].pk);*/
document.getElementById("result").innerHTML = obj.data[0]['pk'];
}
}
xhr.open('POST', uploadAudio_url , true)
//alert(uploadAudio_url)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function () {
// __log("Audio Uploaded to server succesfully");
};
xhr.onerror = function (e) {
// __log("Error Uploading audio" + e)
};
xhr.send(fd);
});
}
I send the blob data which it is an audio file in order to process speech in the backend. The backend process the audio file and filter the objects properly. Then it response to the client with a queryset in JSON. I have interested in get the objects PK and show images in a gallery grid.
This is my
Views.py:
def process_speech(recognized_audio):
speech = recognized_audio
url = '' # Is the URL where the user will be redirected once speech is proccessed
keylist =
for key in Keyword.objects.all():
if(speech.find(key.keyword.lower()) != -1):
keylist.append(key.keyword)
print('Identificado Keyword: ', keylist)
if (speech.find('fotos') != -1 or speech.find('fotografías') != -1):
print("Reconocido FOTO")
imagenes_filtered = Imagen.objects.filter(keyword__keyword__in=keylist)
#print(imagenes_filtered)
return imagenes_filtered
if (speech.find('video') != -1):
print("Reconocido VIDEO")
def upload(request):
print("Método: ", request.method)
print("Ajax: ", request.is_ajax())
if request.method == 'POST':
if request.FILES.get('audio'):
record_audio = request.FILES['audio']
fs = FileSystemStorage()
filename = fs.save(record_audio.name + ".wav", record_audio)
uploaded_file_url = fs.url(filename)
print("File received succesfully")
speech = decodeSpeech(filename)
print(speech)
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(JsonResponse({'data': data}, safe=False),)
else:
return render_to_response('index.html', {"errors":"No recognized audio"})
else:
return HttpResponseRedirect('/home/')
The Json data i get is as follow:
[
{
"model": "Galeria.imagen",
"pk": 20,
"fields":
{"image_width": 6000,
"image_height": 4000,
"fichero_imagen": "files/img/lucas-albuquerque-615558-unsplash.jpg",
"keyword": [17, 18]}
},
{
"model": "Galeria.imagen",
"pk": 21,
"fields":
{"image_width": 5855,
"image_height": 3860,
"fichero_imagen": "files/img/freestocks-org-794156-unsplash.jpg",
"keyword": [18]}
}
]
I have tried things like:
- obj.data[0].pk
- obj.data[0][pk]
- obj.data[0].['pk']
- obj.data.pk[0]
and so on, but I always get undefined.
Thanks in advance
javascript arrays json ajax django
I'm not able to access primary key of an object serialized by Django in JSON. My JavaScript looks like:
function makeLink() {
recorder && recorder.exportWAV(function (blob) {
let fd = new FormData;
fd.append("audio", blob);
let csrftoken = getCookie('csrftoken');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
/*console.log(obj[0].pk);*/
document.getElementById("result").innerHTML = obj.data[0]['pk'];
}
}
xhr.open('POST', uploadAudio_url , true)
//alert(uploadAudio_url)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function () {
// __log("Audio Uploaded to server succesfully");
};
xhr.onerror = function (e) {
// __log("Error Uploading audio" + e)
};
xhr.send(fd);
});
}
I send the blob data which it is an audio file in order to process speech in the backend. The backend process the audio file and filter the objects properly. Then it response to the client with a queryset in JSON. I have interested in get the objects PK and show images in a gallery grid.
This is my
Views.py:
def process_speech(recognized_audio):
speech = recognized_audio
url = '' # Is the URL where the user will be redirected once speech is proccessed
keylist =
for key in Keyword.objects.all():
if(speech.find(key.keyword.lower()) != -1):
keylist.append(key.keyword)
print('Identificado Keyword: ', keylist)
if (speech.find('fotos') != -1 or speech.find('fotografías') != -1):
print("Reconocido FOTO")
imagenes_filtered = Imagen.objects.filter(keyword__keyword__in=keylist)
#print(imagenes_filtered)
return imagenes_filtered
if (speech.find('video') != -1):
print("Reconocido VIDEO")
def upload(request):
print("Método: ", request.method)
print("Ajax: ", request.is_ajax())
if request.method == 'POST':
if request.FILES.get('audio'):
record_audio = request.FILES['audio']
fs = FileSystemStorage()
filename = fs.save(record_audio.name + ".wav", record_audio)
uploaded_file_url = fs.url(filename)
print("File received succesfully")
speech = decodeSpeech(filename)
print(speech)
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(JsonResponse({'data': data}, safe=False),)
else:
return render_to_response('index.html', {"errors":"No recognized audio"})
else:
return HttpResponseRedirect('/home/')
The Json data i get is as follow:
[
{
"model": "Galeria.imagen",
"pk": 20,
"fields":
{"image_width": 6000,
"image_height": 4000,
"fichero_imagen": "files/img/lucas-albuquerque-615558-unsplash.jpg",
"keyword": [17, 18]}
},
{
"model": "Galeria.imagen",
"pk": 21,
"fields":
{"image_width": 5855,
"image_height": 3860,
"fichero_imagen": "files/img/freestocks-org-794156-unsplash.jpg",
"keyword": [18]}
}
]
I have tried things like:
- obj.data[0].pk
- obj.data[0][pk]
- obj.data[0].['pk']
- obj.data.pk[0]
and so on, but I always get undefined.
Thanks in advance
function makeLink() {
recorder && recorder.exportWAV(function (blob) {
let fd = new FormData;
fd.append("audio", blob);
let csrftoken = getCookie('csrftoken');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
/*console.log(obj[0].pk);*/
document.getElementById("result").innerHTML = obj.data[0]['pk'];
}
}
xhr.open('POST', uploadAudio_url , true)
//alert(uploadAudio_url)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function () {
// __log("Audio Uploaded to server succesfully");
};
xhr.onerror = function (e) {
// __log("Error Uploading audio" + e)
};
xhr.send(fd);
});
}
function makeLink() {
recorder && recorder.exportWAV(function (blob) {
let fd = new FormData;
fd.append("audio", blob);
let csrftoken = getCookie('csrftoken');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
/*console.log(obj[0].pk);*/
document.getElementById("result").innerHTML = obj.data[0]['pk'];
}
}
xhr.open('POST', uploadAudio_url , true)
//alert(uploadAudio_url)
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function () {
// __log("Audio Uploaded to server succesfully");
};
xhr.onerror = function (e) {
// __log("Error Uploading audio" + e)
};
xhr.send(fd);
});
}
javascript arrays json ajax django
javascript arrays json ajax django
asked Nov 25 '18 at 3:33
Antonio MaestreAntonio Maestre
487
487
Is that really the JSON? There are inconsistencies
– Randy Casburn
Nov 25 '18 at 3:45
Well, I generate it according to Django Docs about how to serialize objects so the JSON is generated by Django. Why it is wrong? Im new with JSON.
– Antonio Maestre
Nov 25 '18 at 3:52
I'm not saying it is wrong, I'm saying that you show the root of your JSON data as an array ([
), yet you access the parsed JSON asobj.data
. So what does the complete JSON string look like? So in the commented out console log, what do you get if youconsole.log()
onlyobj
?
– Randy Casburn
Nov 25 '18 at 4:23
tryobj.data[0]['pk']
no dot. Maybeobj.data[0][0]['pk']
– Red Cricket
Nov 25 '18 at 4:37
Oh and it is not json is a python list of dictionaries.
– Red Cricket
Nov 25 '18 at 5:02
|
show 5 more comments
Is that really the JSON? There are inconsistencies
– Randy Casburn
Nov 25 '18 at 3:45
Well, I generate it according to Django Docs about how to serialize objects so the JSON is generated by Django. Why it is wrong? Im new with JSON.
– Antonio Maestre
Nov 25 '18 at 3:52
I'm not saying it is wrong, I'm saying that you show the root of your JSON data as an array ([
), yet you access the parsed JSON asobj.data
. So what does the complete JSON string look like? So in the commented out console log, what do you get if youconsole.log()
onlyobj
?
– Randy Casburn
Nov 25 '18 at 4:23
tryobj.data[0]['pk']
no dot. Maybeobj.data[0][0]['pk']
– Red Cricket
Nov 25 '18 at 4:37
Oh and it is not json is a python list of dictionaries.
– Red Cricket
Nov 25 '18 at 5:02
Is that really the JSON? There are inconsistencies
– Randy Casburn
Nov 25 '18 at 3:45
Is that really the JSON? There are inconsistencies
– Randy Casburn
Nov 25 '18 at 3:45
Well, I generate it according to Django Docs about how to serialize objects so the JSON is generated by Django. Why it is wrong? Im new with JSON.
– Antonio Maestre
Nov 25 '18 at 3:52
Well, I generate it according to Django Docs about how to serialize objects so the JSON is generated by Django. Why it is wrong? Im new with JSON.
– Antonio Maestre
Nov 25 '18 at 3:52
I'm not saying it is wrong, I'm saying that you show the root of your JSON data as an array (
[
), yet you access the parsed JSON as obj.data
. So what does the complete JSON string look like? So in the commented out console log, what do you get if you console.log()
only obj
?– Randy Casburn
Nov 25 '18 at 4:23
I'm not saying it is wrong, I'm saying that you show the root of your JSON data as an array (
[
), yet you access the parsed JSON as obj.data
. So what does the complete JSON string look like? So in the commented out console log, what do you get if you console.log()
only obj
?– Randy Casburn
Nov 25 '18 at 4:23
try
obj.data[0]['pk']
no dot. Maybe obj.data[0][0]['pk']
– Red Cricket
Nov 25 '18 at 4:37
try
obj.data[0]['pk']
no dot. Maybe obj.data[0][0]['pk']
– Red Cricket
Nov 25 '18 at 4:37
Oh and it is not json is a python list of dictionaries.
– Red Cricket
Nov 25 '18 at 5:02
Oh and it is not json is a python list of dictionaries.
– Red Cricket
Nov 25 '18 at 5:02
|
show 5 more comments
1 Answer
1
active
oldest
votes
The issue is that you're serializing your data into JSON twice. Once with data = serializers.serialize('json', objects)
and again with JsonResponse({'data': data})
. Creating the JsonResponse
escapes the JSON from the first call turning the list into a big string.
You'll need to remove the nested JsonResponse
and pass the JSON directly.
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(data) # Pass the JSON direct to the HttpResponse
You'll then need to modify your Javascript so that it expects the top level object to be a list (no data
property):
document.getElementById("result").innerHTML = obj[0]['pk'];
Thanks! It works fine.
– Antonio Maestre
Nov 25 '18 at 19:49
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464417%2fhow-access-json-object-serialized-by-django%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The issue is that you're serializing your data into JSON twice. Once with data = serializers.serialize('json', objects)
and again with JsonResponse({'data': data})
. Creating the JsonResponse
escapes the JSON from the first call turning the list into a big string.
You'll need to remove the nested JsonResponse
and pass the JSON directly.
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(data) # Pass the JSON direct to the HttpResponse
You'll then need to modify your Javascript so that it expects the top level object to be a list (no data
property):
document.getElementById("result").innerHTML = obj[0]['pk'];
Thanks! It works fine.
– Antonio Maestre
Nov 25 '18 at 19:49
add a comment |
The issue is that you're serializing your data into JSON twice. Once with data = serializers.serialize('json', objects)
and again with JsonResponse({'data': data})
. Creating the JsonResponse
escapes the JSON from the first call turning the list into a big string.
You'll need to remove the nested JsonResponse
and pass the JSON directly.
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(data) # Pass the JSON direct to the HttpResponse
You'll then need to modify your Javascript so that it expects the top level object to be a list (no data
property):
document.getElementById("result").innerHTML = obj[0]['pk'];
Thanks! It works fine.
– Antonio Maestre
Nov 25 '18 at 19:49
add a comment |
The issue is that you're serializing your data into JSON twice. Once with data = serializers.serialize('json', objects)
and again with JsonResponse({'data': data})
. Creating the JsonResponse
escapes the JSON from the first call turning the list into a big string.
You'll need to remove the nested JsonResponse
and pass the JSON directly.
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(data) # Pass the JSON direct to the HttpResponse
You'll then need to modify your Javascript so that it expects the top level object to be a list (no data
property):
document.getElementById("result").innerHTML = obj[0]['pk'];
The issue is that you're serializing your data into JSON twice. Once with data = serializers.serialize('json', objects)
and again with JsonResponse({'data': data})
. Creating the JsonResponse
escapes the JSON from the first call turning the list into a big string.
You'll need to remove the nested JsonResponse
and pass the JSON directly.
objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(data) # Pass the JSON direct to the HttpResponse
You'll then need to modify your Javascript so that it expects the top level object to be a list (no data
property):
document.getElementById("result").innerHTML = obj[0]['pk'];
edited Nov 25 '18 at 10:30
answered Nov 25 '18 at 10:16
Will KeelingWill Keeling
12.7k22736
12.7k22736
Thanks! It works fine.
– Antonio Maestre
Nov 25 '18 at 19:49
add a comment |
Thanks! It works fine.
– Antonio Maestre
Nov 25 '18 at 19:49
Thanks! It works fine.
– Antonio Maestre
Nov 25 '18 at 19:49
Thanks! It works fine.
– Antonio Maestre
Nov 25 '18 at 19:49
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464417%2fhow-access-json-object-serialized-by-django%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Is that really the JSON? There are inconsistencies
– Randy Casburn
Nov 25 '18 at 3:45
Well, I generate it according to Django Docs about how to serialize objects so the JSON is generated by Django. Why it is wrong? Im new with JSON.
– Antonio Maestre
Nov 25 '18 at 3:52
I'm not saying it is wrong, I'm saying that you show the root of your JSON data as an array (
[
), yet you access the parsed JSON asobj.data
. So what does the complete JSON string look like? So in the commented out console log, what do you get if youconsole.log()
onlyobj
?– Randy Casburn
Nov 25 '18 at 4:23
try
obj.data[0]['pk']
no dot. Maybeobj.data[0][0]['pk']
– Red Cricket
Nov 25 '18 at 4:37
Oh and it is not json is a python list of dictionaries.
– Red Cricket
Nov 25 '18 at 5:02