I have this JSon string received from an AJAX call:
{status:OK,addresses:[0,1,2,3,4,5]}
To convert it to a JSon object I have this line:
var jsonObj = eval(jsonString);
But an exception is thrown! This one has no message in the exception variable.
I also tried using
{"status":"OK","addresses":[0,1,2,3,4,5]}
And, yet again, an exception is thrown but saying that an unexpected character '&' was found.
I'm using Struts2 and the JSon is received from an action.
Any help will be appreciated.
Thank you
{status:OK,addresses:[0,1,2,3,4,5]}
is not valid JSON because the quotes around status and addresses are missing, and is neither valid JSON nor valid JavaScript since the quotes around OK are missing.
Also, don't use eval to parse JSON - it allows an attacker to execute arbitrary JavaScript in the context of your page. Instead, use the safe alternatives JSON.parse(built-in in modern browsers and other EcmaScript 5 implementations) or JSON2.
Don't use eval: use a proper JSON parser such as JSON2.
You probably have extra content in the response: check that you are not printing anything else out.
This is working for me:
JSON.parse('{ "status" : "OK", "addresses" : [0,1,2,3,4,5]}');
If you want to use eval, then you need to use the second example you posted ({"status":"OK","addresses":[0,1,2,3,4,5]}) and you need to surround the string with parenthesis as such:
var jsonObj = eval( '('+jsonString+')' );
This makes jsonString a valid javascript statement.
With that being said, I encourage you use JSON.parse, as many others have posted. It is far more secure.
You don't have a JSON string. You do have an object literal. You need the names to have quotes.
{"status":OK, "addresses":[0,1,2,3,4,5]}
Based on this comment:
So I verified that when JSon is received from the request, all the " are replaced by " ... could this be the problem?
Yes. A JSON parser expects to receive JSON as input, not HTML encoded JSON.
Two issues to fix:
Add quotes around the "OK" to make it a legal javascript string.
Add parens around the string before sending to eval like this eval("(" + jsonString + ")")';
This:
{status:OK,addresses:[0,1,2,3,4,5]}
would have to be changed to this:
{status:"OK",addresses:[0,1,2,3,4,5]}
to be valid Javascript (note the quotes around "OK").
It should be this to be valid JSON (quotes around the keys too):
{"status":"OK", "addresses":[0,1,2,3,4,5]}
OK all by itself is not a known piece of Javascript without the quotes around it to make it into a Javascript string. In the future, you can test yourself in a small test bed and see what the error is in your favorite javascript debugger:
http://jsfiddle.net/jfriend00/FcSKR/
var jsonString = '{"status":"OK","addresses":[0,1,2,3,4,5]}';
var jsonObj = eval("(" + jsonString + ")");
alert("success");
If you still get an error with {"status":"OK","addresses":[0,1,2,3,4,5]} and the adding of parens before sending to eval, then your data isn't what you think it is and you need to do some debugging to see exactly what is in the response (look at the value in the debugger, put the value into an alert, etc...). There is probably some other stuff in the response that you didn't know would be there.
Note: there are some situations where a JSON parser like JSON.parse() and a legal JSON string is safer than eval() with Javascript that can be anything.
Related
I'm fetching JSON code stored in MySQL and it has extra slashes, which I have to remove in order to parse it in JavaScript, after I print it on the page. Right now I'm doing the following:
$save = str_replace("\n", "<br>", $save); // Replace new line characters with <br>
$save = str_replace('\\"', '"', $save); // top-level JSON
$save = str_replace('\\\\"', '\"', $save); // HTML inside top level JSON
$save = str_replace('\\\\\\\\\\"', '\\\\\"', $save); // HTML inside second level JSON
Here is an example JSON code, as it comes out from MySQL:
{\"id\":2335,\"editor\":{\"selected_shape\":\"spot-7488\"},\"general\":{\"name\":\"HTML Test\",\"shortcode\":\"html-test\",\"width\":1280,\"height\":776},\"spots\":[{\"id\":\"spot-7488\",\"x\":9.9,\"y\":22.6,\"default_style\":{\"use_icon\":1},\"tooltip_content\":{\"content_type\":\"content-builder\",\"plain_text\":\"<p class=\\\"test\\\">Test</p>\",\"squares_json\":\"{\\\"containers\\\":[{\\\"id\\\":\\\"sq-container-293021\\\",\\\"settings\\\":{\\\"elements\\\":[{\\\"settings\\\":{\\\"name\\\":\\\"Paragraph\\\",\\\"iconClass\\\":\\\"fa fa-paragraph\\\"},\\\"options\\\":{\\\"text\\\":{\\\"text\\\":\\\"<p class=\\\\\\\"test\\\\\\\">Test</p>\\\"}}}]}}]}\"}}]}
And here is how it's supposed to look in order to get parsed correctly (using jsonlint.com to test):
{"id":2335,"editor":{"selected_shape":"spot-7488"},"general":{"name":"HTML Test","shortcode":"html-test","width":1280,"height":776},"spots":[{"id":"spot-7488","x":9.9,"y":22.6,"default_style":{"use_icon":1},"tooltip_content":{"content_type":"content-builder","plain_text":"<p class=\"test\">Test</p>","squares_json":"{\"containers\":[{\"id\":\"sq-container-293021\",\"settings\":{\"elements\":[{\"settings\":{\"name\":\"Paragraph\",\"iconClass\":\"fa fa-paragraph\"},\"options\":{\"text\":{\"text\":\"<p class=\\\"test\\\">Test</p>\"}}}]}}]}"}}]}
Please note that I have HTML code inside JSON, which is inside another JSON and this is where it gets a bit messy.
My question - is there a function or library for PHP (for JS will work too) which covers all those corner cases, because I'm sure someone will find a way to break the script.
Thanks!
The short answer, which is woefully inadequate, is for you to use stripslashes. The reason this answer is not adequate is that your JSON string might have been escaped or had addslashes called on it multiple times and you would have to call stripslashes precisely once for each time this had happened.
The proper solution is to find out where the slashes are being added and either a) avoid adding the slashes or b) understand why the slashes are there and respond accordingly. I strongly believe that the process that creates that broken JSON is where the problem lies.
Slashes are typically added in PHP in a few cases:
magic_quotes are turned on. This is an old PHP feature which has been removed. The basic idea is that PHP used to auto-escape quotes in incoming requests to let you just cram incoming strings into a db. Guess what? NOT SAFE.
add_slashes has been called. Why call this? Some folks use it as an incorrect means of escaping data before sticking stuff in a db. Others use it to keep HTML from breaking when echoing variables out (htmlspecialchars should probably be used instead). It can also come in handy in a variety of other meta situations when you are defining code in a string.
When escaping data input. The most common escaping function is mysqli_real_escape_string. It's very important to escape values before inserting them in a db to prevent sql injection and other exploits but you should never escape things twice.
So there's a possibility that your code is double-escaping things or that addslashes is getting called or something like magic_quotes is causing the problem, but I suspect it is another problem: some JS code might be supplying this JSON not as a proper JSON string, but one that has been escaped so to define a string within javascript.
If you take your example JSON string above, and slap some quotes around it:
var myJSON = "<put your string here>";
then SURPRISE your javascript is not broken and the var myJSON contains a string that is actually valid JSON and can be parsed into an a valid JSON object:
var myJSON = "{\"id\":2335,\"editor\":{\"selected_shape\":\"spot-7488\"},\"general\":{\"name\":\"HTML Test\",\"shortcode\":\"html-test\",\"width\":1280,\"height\":776},\"spots\":[{\"id\":\"spot-7488\",\"x\":9.9,\"y\":22.6,\"default_style\":{\"use_icon\":1},\"tooltip_content\":{\"content_type\":\"content-builder\",\"plain_text\":\"<p class=\\\"test\\\">Test</p>\",\"squares_json\":\"{\\\"containers\\\":[{\\\"id\\\":\\\"sq-container-293021\\\",\\\"settings\\\":{\\\"elements\\\":[{\\\"settings\\\":{\\\"name\\\":\\\"Paragraph\\\",\\\"iconClass\\\":\\\"fa fa-paragraph\\\"},\\\"options\\\":{\\\"text\\\":{\\\"text\\\":\\\"<p class=\\\\\\\"test\\\\\\\">Test</p>\\\"}}}]}}]}\"}}]}";
console.log(JSON.parse(myJSON)); // this is an actual object
The key here is to examine the point of entry where this JSON arrives in your system. I suspect some AJAX request has created some object and rather than sending valid JSON Of that object, it is sending instead an escaped string of a JSON object.
EDIT:
Here's a simple example of what happens when you have too many encodings. Try running this JS in your browser and observe the console output:
var myObj = {"key":"here is my value"};
console.log(myObj);
var myJSON = JSON.stringify(myObj);
console.log(myJSON);
var doubleEncoded = JSON.stringify(myJSON);
console.log(doubleEncoded);
I am using jquery CSV library (https://github.com/evanplaice/jquery-csv/) , to parse and convert a CSV file into an array of objects. This is my code
this.parsedData = $.csv.toObjects(data);
if (this.parsedData.length === 0) {
**console.log('In valid'); /**/ This gets printed
} else {
console.log('valid')
}
My CSV file is this:
""__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream""
Now, if I remove quotes, it works fine, but with quotes it doesn't.
Most of the time, my application is going to handle CSV with values in quotes.
Is there any way to fix it?
Try with http://papaparse.com/; you can parse it online and it works great.
All you have to do is call through var results = $.parse(csvString);
and it will return the JSON object for you.
Why is it wrapped in quotes?
I've tested it without the outer quotes on the Basic Usage demo and it seems to parse the data just fine. Are you using at least version 0.71?
This:
""__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream""
Double-double quotes cancel each out (as per the spec) so this'll error when it tries to parse the first value.
Should be:
"__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream"
If jquery-csv encounters an error during parsing it should log an error to the console indicating the row:column where the error occurred. Is there an error in the console. If not what does console.log(data) output?
As for the data being a mix of quoted/unquoted, the parser shouldn't have any issues consuming it. The data (sans outer quotes) looks perfectly valid.
BTW, I'm not trying to shed blame. If there is something else here that isn't in the code sample you provided that exposes a bug in the parser, I'd like to identify and fix it.
Disclaimer: I'm the author of jquery-csv
I use JQuery to get Json data, but the data it display has double quotes. It there a function to remove it?
$('div#ListingData').text(JSON.stringify(data.data.items[0].links[1].caption))
it returns:
"House"
How can I remove the double quote? Cheers.
Use replace:
var test = "\"House\"";
console.log(test);
console.log(test.replace(/\"/g, ""));
// "House"
// House
Note the g on the end means "global" (replace all).
For niche needs when you know your data like your example ... this works :
JSON.parse(this_is_double_quoted);
JSON.parse("House"); // for example
The stringfy method is not for parsing JSON, it's for turning an object into a JSON string.
The JSON is parsed by jQuery when you load it, you don't need to parse the data to use it. Just use the string in the data:
$('div#ListingData').text(data.data.items[0].links[1].caption);
Someone here suggested using eval() to remove the quotes from a string. Don't do that, that's just begging for code injection.
Another way to do this that I don't see listed here is using:
let message = JSON.stringify(your_json_here); // "Hello World"
console.log(JSON.parse(message)) // Hello World
I also had this question, but in my case I didn't want to use a regex, because my JSON value may contain quotation marks. Hopefully my answer will help others in the future.
I solved this issue by using a standard string slice to remove the first and last characters. This works for me, because I used JSON.stringify() on the textarea that produced it and as a result, I know that I'm always going to have the "s at each end of the string.
In this generalized example, response is the JSON object my AJAX returns, and key is the name of my JSON key.
response.key.slice(1, response.key.length-1)
I used it like this with a regex replace to preserve the line breaks and write the content of that key to a paragraph block in my HTML:
$('#description').html(studyData.description.slice(1, studyData.description.length-1).replace(/\\n/g, '<br/>'));
In this case, $('#description') is the paragraph tag I'm writing to. studyData is my JSON object, and description is my key with a multi-line value.
You can simple try String(); to remove the quotes.
Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp
Thank me later.
PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.
What you are doing is making a JSON string in your example. Either don't use the JSON.stringify() or if you ever do have JSON data coming back and you don't want quotations, Simply use JSON.parse() to remove quotations around JSON responses! Don't use regex, there's no need to.
I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link
Example :
success: function (data) {
// assuming that everything is correct and there is no exception being thrown
// output string {"d":"{"username":"hi","email":"hi#gmail.com","password":"123"}"}
// now we need to remove the double quotes (as it will create problem and
// if double quotes aren't removed then this JSON string is useless)
// The output string : {"d":"{"username":"hi","email":"hi#gmail.com","password":"123"}"}
// The required string : {"d":{username:"hi",email:"hi#gmail.com",password:"123"}"}
// For security reasons the d is added (indicating the return "data")
// so actually we need to convert data.d into series of objects
// Inbuilt function "JSON.Parse" will return streams of objects
// JSON String : "{"username":"hi","email":"hi#gmail.com","password":"123"}"
console.log(data); // output : Object {d="{"username":"hi","email":"hi#gmail.com","password":"123"}"}
console.log(data.d); // output : {"username":"hi","email":"hi#gmail.com","password":"123"} (accessing what's stored in "d")
console.log(data.d[0]); // output : { (just accessing the first element of array of "strings")
var content = JSON.parse(data.d); // output : Object {username:"hi",email:"hi#gmail.com",password:"123"}" (correct)
console.log(content.username); // output : hi
var _name = content.username;
alert(_name); // hi
}
I had similar situation in a Promise just solved doing a cast as (String)
export async function getUserIdByRole(userRole: string): Promise<string> {
const getRole = userData.users.find((element) => element.role === userRole);
return String (getRole?.id);
}
can someone tell me the fastest way to parse a json string to an object without jquery?
I want to parse the json string in a script tag before jquery is loaded.
Thanks in advance!
Peter
Use JSON JS
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
var myObject = eval('(' + myJSONtext + ')');
taken from http://www.json.org/js.html
var myObject = eval('(' + myJSONtext + ')');
If the JSON string comes from the server you can try the JSONP technique. The JSON is parsed natively in the browser(fast) when loaded and without any library.
eg: if you response is {"name":"Peter"}
A JSONP response will be something like:yourFunction({"name":"Peter"})
yourFunction must be a globally defined function in the page that will receive the call, like:
function yourFunction(json){
//do something with the JSON
}
I am really stuck in parsing a JSON string and take it's values. I got the JSON string as
{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}
How to Parse this and take the Results for further
processing in JavaScript
You should use jQuery.parseJSON. It will use native JSON if available, and only use eval if necessary, after a sanity check.
Use JSON.parse (redirected from http://json.org), alternatively MDN
Json is already some javascript. so parsing is just using eval
like:
var foobar = eval(yourjson);
alert(foobar.user);
Also jquery has some function for it jquery.parseJSON
like:
var foobar = $.parseJSON(yourjson);
Jquery is better because it would make some checks and perform better.
First, download jQuery.
Second, include it in your page.
Third, if your variable is this:
var jsonString = '{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}';
then,
var parsedJson = jQuery.parseJSON(jsonString);
will give you the desired parsed object that's ready for manipulation.
I tried out your JSON string on JSONLint and it says it's valid, so you should have no problems with it.
you probably got your json in som String variable
var json = '{"user":{"id":"1","firstname":"Freelogin","created":"0000-00-00 00:00:00","lastname":"Administrator","email":"fred#websecurify.com", "usergroup_id":"1","status":"1","ip_enable":"N","priv":"0","expire":""},"data":{ "1":{"5":{"last_update":"2010-12-13 16:16:16","status":"0"},"3":{"last_update":"2010-12-13 16:41:48","status":"1"}},"2":{"6":{"last_update":"2010-12-13 16:41:48","status":"1"}}},"server_array":[{"id":"1","name":"anes.yyy.net"},{ "id":"2","name":"neseema.xxx.net"}],"service_array":[{"id":"5","name":"POP3"}, {"id":"6","name":"Cpanel"},{"id":"3","name":"SMTP"}],"sort_by":"servername", "sort_order":"ASC","pagelinks":"","totrows":"2","offset":"0","limitvalue":"10", "rows_monitor":2,"current":"monitor","uri":false}';
now you can easily parse it via jQuery (you also can parse it via native javaScript eval, but there are some security issues, badly formated input string f.e., that is covered with jQuery and not in eval)
result = jQuery.parseJSON(json);
Now you can easily acces your json object
alert('Hello user, your name is ' + json.user.firstname);
You don't need jQuery, in ECMAScript5 JSON object will be supported natively and with it you can use JSON.parse method to parse a string into a JS object. IE9 will support ES5 and FF and Chrome already do.
For the moment you can use json2.js (you can look at the source here) as fallback for the browsers that don't support JSON natively.