Correcting JSON string with incorrect notation? - javascript

I'm working on a web application witch javascript, and I have to receive and parse a JSON string that looks like this:
{name:"", house:""}
What's the best way to convert it to proper notation?
{"name":"", "house":""}
Thanks in advance!

var str = '{name:"", house:""}';
var newStr = JSON.stringify( eval( '(' + str + ')' ) );
console.log(newStr); //{"name":"", "house":""}
Fiddle
Do not use eval if the data source is untrusted though.
By the way, are you sure you're receiving a badly formed JSON string and it is not just an object? In case you're using jQuery, it automatically parses JSON responses into objects. In that case you'd just call JSON.stringify passing the object to make a valid JSON string from it, or access the request's responseText. Fiddle with jQuery Ajax.

Related

JSON Parsing error with backslash

I have been trying to figure out why the following JSON input will be failed to parse in JSON.parse function.
{"World":"Hello\\Test"}
The json above is being returned by JSON.NET.
I have tried multiple methods to get this working. As you can see the backslash is escaped and https://jsonlint.com/ is able to parse it.
I have a failing sample at https://jsfiddle.net/ckp0uc0p/3/ as well.
Any help will be appreciated.
The best way to inject JSON into JavaScript source code (when generating the JavaScript with a server side language), is to inject it directly where you need it, not inside a string literal that needs to be parsed.
For example:
var foo = <json blob>;
so that the result will be
var foo = {"World":"Hello\\Test"};
JavaScript will interpret this as an object literal resulting in an object, which is what you want to get anyway. This avoids all the problems with "nested" escape sequences.
You need to add two \\ for every backslash you want to have it displayed. If you're parsing a json, to display 2 backslashes you need to add 4.
// inside a string to be parsed as json
var json = '{"World":"Hello\\\\Test"}'
console.log(JSON.parse(json))
// directly in an object
var object = {"World": "Hello\\Test"}
console.log(object)
try
{
var res = '{"World":"Hello\\\\Test"}';
var s = JSON.parse(res);
console.log(JSON.stringify(s));
} catch(error) {
alert(error);
}

Parsing JSON with Javascript

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.

Fastest way to parse a json strings (without jquery)

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
}

Yet i'm finding difficult to understand JSON

hey guys, i have read This post, so what i got is JSON is the easiest way to translate a JavaScript object into a PHP/C# associative array or object (and vice-versa).
Now my question is what is goin' on in below code,i.e without JSON/XML i'm still can access my C# object in Javascript, may be i'm wrong, if so Please correct me:
C#
Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
{
strItems &= "'" & dr("ItemTitle") & "'," //strItems is a String
}
strItems = strItems.Trim(",")
Javascript : here i'm using Autocomplete.js using JQuery
function InitAutocomplete()
{
data = [<%=strItems %>].sort();
AutoComplete_Create('<%=txtItem.ClientId %>', data);
}
See i'm using strItems in javascript with servertag, so where exactly the JSON is used ? is .net doin' something internally ? i'm totally confused how JSON/XML is used to data passing ?
While you can pass data like this without using JSON, it doesn't ensure that all of the data is safe to pass, e.g. embedded </script> tags. Using JSON will encode your data in a way that prevents this, and you decode it on the JavaScript side with e.g. json2.js.
You're not really using JSON in anything here. You're merely generating an array of strings for javascript and use it in a vvery straightforward manner.
If you wish to transform the JSON to javascript object(s) you need to modify your program and you need a JSON parser. There are several implementations of JSON-parsers, but you mentioned jQuery so you could use: http://api.jquery.com/jQuery.parseJSON/
Parsing with jQuery, however, requires your JSON to be strictly formatted (from v1.4). See http://json.org/ about the correct form. Basically in your situation you should put double quotes around your strings and put the whole array inside square brackets.
Your results should be something like this:
strItems = '['
Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
{
// TODO: Escape dr("ItemTitle") so it conforms to http://json.org/ => String
strItems &= "\"" & dr("ItemTitle") & "\"," //strItems is a String
}
strItems = strItems.Trim(",")
strItems &= ']'
<script type="text/javascript">
var jsonArr = <%=strItems%>;
var data = jQuery.parseJSON(jsonArr);
AutoComplete_Create('<%=txtItem.ClientId %>', data);
</script>

How to parse JSON in JavaScript to take value

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.

Categories

Resources