Django/JS: json.dumps and parse.json - javascript

I'm no programmer, so I can't go to source code of Django or Jquery and figure out how and why these function don't return what I want from them, because I simply wouldn't understand the source code.
I do one little project for myself and here's my confusion about json part:
here's my django/python function:
def searchPatients(request):
patients = Patients.objects.filter(KeyName__icontains=request.POST.get('KeyName'))
response = []
for patient in patients:
tmpvar = {}
tmpvar = { 'Name1':patient.Name1, 'Name2':patient.Name2 }
response.append(tmpvar)
return HttpResponse(json.dumps(response), content_type="application/json")
I checked in shell, json.dumps(response) gave me this:
'[{"Name2": "TestName2", "Name1": "TestName1"}, {"Name2": "TempName2", "Name1": "TempName1"}]'
Looks ok form me. And then I don't understand part starts. This is my JS/JQuery function:
input_newRecord_Search.keyup(function() {
$.post('/edit/ajax_search_patients', { KeyName: $(this).val() }, function(data) {
var patients = jQuery.parseJSON(data);
for (var patient in patients) {
$('#searchResults ul').append('<li>'+patients[patient].Name1+'</li><li>+'patients[patient].Name2+'</li>');
};
}, "json");
});
I get an error: "SyntaxError: JSON.parse: unexpected character".
I checked what data jquery gets from server: console.log(data):
[{Name2: "TestName2", Name1: "TestName1"}, {Name2: "TempName2", Name1: "TempName1"}]
So, as far as I know JSON syntax looks like - {"key":"value"} and I'm missing quotes on key field. And I don't understand why I'm missing them. I can put them manually through regex, for instance, but I don't think it's the right way. And using regex I can parse my entire data without need of jQuery.parseJSON(), but again I want to use jQuery function - after all it was made exactly for this purpose.
Can anyone help me with this one?

The trick is that when you tell jQuery.post that the server is returning JSON it parses it for you.
// This line can be safely removed;
// jQuery is doing it for you behind the scenes
var patients = jQuery.parseJSON(data);
When you use parseJSON on the already parsed data you wind up trying to parse the string representation of a JavaScript object. Simply use the already parsed data and everything should work correctly.

jQuery is automatically converting the json to js objects for you. You don't need to call parse yourself.

Related

Retrieving JSON data using the value of a variable

Hello. I'm currently working on a small project and have the following issue that I can't seem to solve alone. I have attempted to search for a solution, with no luck. Admittedly, it doesn't help that I'm fairly new at JavaScript/jQuery, so I'm unsure of the "correct" search terms!
I have a JSON file that contains the following code:
var draft = {
"title": "Title",
"subtitle": "Subtitle",
"image": "/image.jpeg",
}
I'm then retrieving the JSON data with the following line:
draft["title"];
Based upon what the application is required to achieve - is there a way to access the JSON data using the value of a variable in place of "draft"? I have an AJAX function that is pulling the file name and extension of the JSON file, and then the following line of code that is refining the file name down to one word by removing the slashes, numbers, hyphens, and file extension:
var fileNameRefined = fileName.replace("/", "").replace(/\d+|-/g, "").replace(".json", "");
As a result, the "fileNameRefined" variable will contain the value "draft". This outputs to the console as expected. That said, it won't work with the JSON. I was hoping that the following lines of code would work in the exact same way:
draft["title"];
fileNameRefined["title"]; // var fileNameRefined = draft
Unfortunately, the resulting data is returned as "undefined". I'm assuming the application is treating the name of the variable as a string as opposed to passing the variable's value? I'm not sure.
Does anybody have a solution to this? Any help would be greatly appreciated.
Thanks, all.
Could be done, SHOULDN'T be done.
Use JSON (This is JS object you presented) and its API. Here is example for jQuery, there are similar examples for other libs/frameworks.
I would always go with fw or lib here for a clear Ajax API over writing it yourself in vanilla.
Here is get JSON example in fiddle (not written by me):
json get fiddle
function getSuccessOutput() {
$.ajax({
url:'/echo/js/?js=hello%20world!',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
},
});
return false;
}
As for JSON api you will be interested in parsing the response using JSON.parse()
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Someone please tell me what is wrong with my $.parseJSON [javascript / jquery]

Here is my tested result. I run my app, I get the "Hello" alert. But I don't get "After parse JSON" alert.
When I comment out the var rstList = $.parseJSON(data); line, "After parse JSON" alert prompted correctly.
I have check many document and reference but couldn't find out what is wrong with my $.parseJSON(). Please advice, thank you.
//Show restaurant listing
$('#restaurantList').on("pagebeforecreate", function() {
$.getJSON("http://mydomain/api/restaurant", function( data ) {
alert('Hello');
var rstList = $.parseJSON(data);
alert('After parse JSON');
});
});
Contrary to what the name implies, $.getJSON doesn't give you some JSON but the result of the parsing.
From the documentation :
The success callback is passed the returned data, which is typically a
JavaScript object or array as defined by the JSON structure and parsed
using the $.parseJSON() method.
You data is already parsed, don't parse it.
BTW, as Niet commented, you should have looked at the console to have a little more information on the error halting your script's execution. See Using the console.
Because you are trying to parse a json object again. Which causes the error. $.getJSON
will return the json object. You dont need to parse it again

I keep getting "Uncaught SyntaxError: Unexpected token o"

I'm trying to learn some html/css/javascript, so I'm writing myself a teaching project.
The idea was to have some vocabulary contained in a json file which would then be loaded into a table. I managed to load the file in and print out one of its values, after which I began writing the code to load the values into the table.
After doing that I started getting an error, so I removed all the code I had written, leaving me with only one line (the same line that had worked before) ... only the error is still there.
The error is as follows:
Uncaught SyntaxError: Unexpected token o
(anonymous function)script.js:10
jQuery.Callbacks.firejquery-1.7.js:1064
jQuery.Callbacks.self.fireWithjquery-1.7.js:1182
donejquery-1.7.js:7454
jQuery.ajaxTransport.send.callback
My javascript code is contained in a separate file and is simply this:
function loadPageIntoDiv(){
document.getElementById("wokabWeeks").style.display = "block";
}
function loadWokab(){
//also tried getJSON which threw the same error
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
}
And my JSON file just has the following right now:
[
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
},
{
"english": "glasses",
"kana": "megane",
"kanji": "M"
}
]
Now the error is reported in line 11 which is the var glacier = JSON.parse(data); line.
When I remove the json file I get the error: "GET http://.../wokab.json 404 (Not Found)" so I know it's loading it (or at least trying to).
Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.
Further explanation can be found in Aditya Mittal's answer.
The problem is very simple
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
You're parsing it twice. get uses the dataType='json', so data is already in json format.
Use $.ajax({ dataType: 'json' ... to specifically set the returned data type!
Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.
Parsed data from jquery success handler for text/html response:
var parsed = JSON.parse(data);
Parsed data from jquery success handler for application/json response:
var parsed = data;
Another hints for Unexpected token errors.
There are two major differences between javascript objects and json:
json data must be always quoted with double quotes.
keys must be quoted
Correct JSON
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
}
Error JSON 1
{
'english': 'bag',
'kana': 'kaban',
'kanji': 'K'
}
Error JSON 2
{
english: "bag",
kana: "kaban",
kanji: "K"
}
Remark
This is not a direct answer for that question. But it's an answer for Unexpected token errors. So it may be help others who stumple upon that question.
Simply the response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o" however you have to specify datatype in your request to be of type dataType='json'
I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.
I was accessing the iframe data like this:
$('#load-file-iframe').contents().text()
which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to
$('#load-file-iframe').contents().find('body').text()
once I noticed some garbage in the HTML response.
Long story short check your raw HTML response data and you might turn something up.
SyntaxError: Unexpected token o in JSON
This also happens when you forget to use the await keyword for a method that returns JSON data.
For example:
async function returnJSONData()
{
return "{\"prop\": 2}";
}
var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);
will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.
To fix just add await as you're supposed to:
var json_str = await returnJSONData();
This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.
Make sure your JSON file does not have any trailing characters before or after. Maybe an unprintable one? You may want to try this way:
[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(tempActivity, getCircularReplacer());
Where tempActivity is fething the data which produces the error "SyntaxError: Unexpected token o in JSON at position 1 - Stack Overflow"

Json object in jquery can't be read?

I am trying to read the finance info from the google page into a json object.
Code is below:
try {
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?",function(data){
alert(data);//var jsondata = data;
//jsonobj = $.parseJSON(jsondata);
//alert(jsonobj[0].id);
});
} catch(e) {
alert(e.toString());
}
However I keep getting this error all the time on firebug
invalid label
"id": "4052464"
Is there any way this info can be read. My ultimate goal is to create a windows 7 gadget that doesnt use server side scripting and can be used from any Windows 7 system.
Appreciate all the help.
John
Response isn't valid JSON (response is prefixed with //), so jQuery won't be able to parse it correctly anyway.
To solve change &jsoncallback=? to &callback=?
so
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&callback=?", function(data) {
alert(data)
});
The response from Google has two leading /'s, making the response invalid JSON... for some reason.
Because of this, you cannot use jQuery.getJSON, as it expects a JSON response. Instead, you should use jQuery.get, and parse the JSON yourself after removing the two leading slashes.
jQuery.get('http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?', function (string) {
var validJson = string.slice(2);
var obj = jQuery.parseJSON(validJSON);
// use obj
});
Two additional points:
No JSONP is being used, so you don't need the jsoncallback=? in your request URL
The Windows Sidebar has been retired, so you cannot publish you finished gadget to the official gallery.

Accessing JSON values with a variable

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).
try to list all properties from data, to have sure the data is being returned:
for (var p in data){
if (data.hasOwnProperty(p){
alert(data[p]);
}
}
It's not your solution but with this you can know how your data is coming.

Categories

Resources