I've a string in JSON format. I'm trying to iterate it. I have validate the string whether its JSON or not. It is fine. But, when I try to iterate it, it throws me error .
Here is my
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":"{\"color\": \"blue\",\"value\": \"#f00\"}"},{"id":8,"userId":"123","courseId":"C5","courseValue":"{\"color\": \"green\",\"value\": \"#f00\"}"}]';
Here is the fiddle
http://jsfiddle.net/hLkUz/40/
You have taken some JSON and wrapped ' around it to try to make it a JavaScript string literal.
Some characters have special meaning in JavaScript string literals (such as \ which starts an escape sequence). You have failed to escape them within the string.
Consequently, to take an example:
"{\"color\":…
… when parsed as part of the JavaScript string literal becomes:
"{"color":…
… which isn't valid JSON.
You need to escape the special characters for the JavaScript string literal.
Better yet, restructure your JSON so that it doesn't contain values which are encoded as JSON themselves. Use an object instead of a string containing JSON representing an object.
You are having unwanted double string in values. Corrected json string is here
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{\"color\": \"blue\",\"value\": \"#f00\"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{\"color\": \"green\",\"value\": \"#f00\"}}]';
Try this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
There's no need to wrap the object with " nor escape it.
What you need is this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
Fiddle
I'm not sure if you intend to escape the JSON within courseValue. However it seems like the escaping of the nested objects is the problem. This works
http://jsbin.com/mekiwalidu/edit?js,console,output
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
var obj = JSON.parse(string);
console.log(obj);
Related
I have this string that I want to convert to an JSON object, the problem is that one of the fields of the object is a regex:
"{
\"regex\": /^([a-zA-Z0-9_\\.\\-\\+%])+\\#(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/,
\"alertText\": \"test\"
}"
Is there a way to get the JavaScript object without doing hundreds of replaces?
EDIT: I use the following code to store the correct serialized version of the original object from Stringifying a regular expression?:
RegExp.prototype.toJSON = function() { return this.source; };
Then I could modify the content of the string:
{"regex":"^([a-zA-Z0-9_\\.\\-\\+%])+\\#(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$","alertText":"* {{alertText}}"}
So I can use it as a template, and then, when needed, JSON.parse the string to get a new object.
Simply ensure that your regex value is enclosed with quotes to force it to be a string value:
"{
\"regex\": \"/^([a-zA-Z0-9_\\.\\-\\+%])+\\#(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/\",
\"alertText\": \"test\"
}"
Then, this will parse as a JSON object correctly and you can get the regex out later to create your regex from it.
If you require the slashes double escaped for your regex purposes, then...
"{
\"regex\": \"/^([a-zA-Z0-9_\\\\.\\\\-\\\\+%])+\\\\#(([a-zA-Z0-9\\\\-])+\\\\.)+([a-zA-Z0-9]{2,4})+$/\",
\"alertText\": \"test\"
}"
Solution:
One alternative solution whould be to change/reformat your JSON string, you will simply need to :
Change the enclosing double quotes " with a single quote '.
And use only one backslash \ for escaping.
This is a working DEMO:
var text = '{"regex": "/^([a-zA-Z0-9_\.\-\+%])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", "alertText": "test"}';
var obj=JSON.parse(text);
console.dir(obj);
document.write(obj.regex);
document.write("<br>"+obj.alertText);
The short answer is No.
Answers so far rely on being able to change the string at source. If you can do that, great, but as per the OP, you can't parse the JSON with a regex value using a stock JSON.parse(), even with a reviver function.
What I am trying to do is simple. Parse this array holding json objects into a Javascript array.
var merchantsJson = JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]');
But the unicode character \u003C seems to be breaking the parser. In the chrome console I see "Uncaught SyntaxError: Unexpected token <"
A little more info. The above is what the code is evaluated to. In reality the code contains a jsp expression.
var merchantsJson = JSON.parse('${jsonArr}');
If I remove the single quotes, there is no issue, but eclipse give me an "missing semicolon" error message. Is it possible to parse the array with the quotes as I am trying to do?
The interpolation of ${jsonArr} is already a JavaScript object. When you wrap it in '${jsonArr}' this turns it into a string and you have to use JSON.parse.
There's no need to make it a string. You can just do var merchantsArray = ${jsonArr}. JSON constructs are already interoperable with JavaScript code.
Because there's an extra " in your string literal that is encoded by \u0022:
> '[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]'
[{"id":61693,"name":"Más"},{"id":61690,"name":"'"</div>"}]
In short, your JSON in the string is invalid. You would need to escape the unicode escape sequences for the quotes in the string literal ("'\u0022</div>"), by using
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\u0022\u003C/div\u003E"}]'
// ^
or escape the quote character ("'\"</div>"):
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\\u0022\u003C/div\u003E"}]');
// ^^
However, there actually is no need to use JSON at all. Just output a JS array literal into your code:
var merchantsJson = ${jsonArr};
Try to replace \u with \\u. If you don't, JSON parser receives already decoded Unicode, which created polluted JSON.
It's not because of \u003C, rather the \u0022 character is causing the issue, since it's a quotation mark and JavaScript treats it literally ending the string.
You need to escape that character: \\u0022 .
you have to use special character in your JSON string, you can escape it using \ character.
you need to replace \ with \\.
[{\"id\":61693,\"name\":\"Más\"},{\"id\":61690,\"name\":\"\\u0027\\u0022\\u003C/div\\u003E\"}]
I am using Dojo.fromJson to convert json string to javascript object, but throw exception. Because, there are control characters such as ',\n,\r in the json string.
How can I solve this problem in dojo? convert json string to javascript object, even if there are control characters.
I use Newtonsoft.JsonConvert.SerializeObject to convert C# oject to json data. Json Object: {"name":"'\"abc\n123\r"} then, I use Dojo.fromJson(' {"name":"'\"abc\n123\r"}') to convert json data to javascript object.
Thank you very much!
Problem, i believe is the double-quote which should be escaped by triple backslashes. You can use "native browser JSON decode" as searchterm for "dojo fromJson" synonym.
Without knowing my way around C# - I havent tested but i believe following should work:
string c_sharp_name = "'\"abc\n123\r";
// C#Object.name
c_sharp_name = c_sharp_name.
replace('"', '\\"'). // maybe add a slash on serverside
replace('\n', '\\\n').
replace('\r', '\\\r');
since
while this fails:
{"name":"'\"abc\n123\r"} // your single backslash
this would work:
{"name":"'\\\"abc\\\n123\\\r"} // working triple backslash escape
I got a json structure somehow as below and my question is how can i parse this with jQuery so that i can use it like myJson[0].name and than alert it so that "M\\xe9t\\xe9o" = Météo.
Jquery tells me this is invalid json why ?
Json uses double backslash if i use single backslash ("M\xe9t\xe9o") Jquery is OK with the syntax.
var jsonObj = '{"title":[{"id":"1","name": "M\\xe9t\\xe9o"},{"id":"2","name": "Meteo"}]}';
var myJson = jQuery.parseJSON(jsonObj);
The JSON syntax only allows \uxxxx escapes.
Change it to "M\\u00e9t\\u00e9o".
If you use a single backslash, it gets parsed by the Javascript string literal, so the actual string value contains the real Unicode character, not an escape. In other words, "M\xe9t\xe9o" === "Météo"
It is looks like the json was incorrectly (manually?) encoded. When you encode it in UTF-8, e.g. with PHP, you'll get:
{"title":[{"id":"1","name": "M\u00e9t\u00e9o"},{"id":"2","name": "Meteo"}]}
which is correctly parsed by JS. But \xe9 is unrecognized by parser.
Since the JSON format specifies that single quotes should not be escaped, most libraries (or even the native JSON parser) will fail if you have an escaped single quote in it. Now this usually is not a problem since most of the time you do an XHR that fetches some data formatted as JSON and you use the responseText which contains your JSON string that you can then parse, etc.
In this particular situation, I have a JSON string stored in a database as text... so the database contains something like {"property":"value"} and I want to output this as part of an HTML page created by the server so that the JavaScript code in that page looks something like this:
var x = '{"property":"value"}';
Now if the JSON string in the database contains a single quote like this:
{"property":"val'ue"}
Then I need to escape it or else I will never be able to use it as a string:
console.clear();
var obj = {prop:"val'ue"};
var str = JSON.stringify(obj);
console.log("JSON string is %s",str);
console.dir(JSON.parse(str)); //No problem here
//This obviously can't work since the string is closed and it causes an invalid script
//console.dir(JSON.parse('{prop:"val'ue"}'));
//so I need to escape it to use a literal JSON string
console.dir(JSON.parse('{"prop":"val\'ue"}'));
The question then is why {"prop":"val\'ue"} not considered a valid JSON string ?
In JavaScript - the string '{"prop":"val\'ue"}' is a correct way to encode the JSON as a string literal.
As the JavaScript interpreter reads the single-quoted string, it will convert the \' to '. The value of the string is {"prop":"val'ue"} which is valid JSON.
In order to create the invalid JSON string, you would have to write '{"prop":"val\\\'ue"}'
If I understand the question right, you are trying to generate JavaScript code that will set some variable to the decoded version of a JSON string you have stored in the database. So now you are encoding the string again, as the way to get this string into JavaScript is to use a string literal, passing it through JSON.parse(). You can probably rely on using the server side JSON encoder to encode the JSON string as a JavaScript string literal. For instance:
<?php $jsonString = '{"prop":"val\'ue"}'; ?>
var myJson = JSON.parse(<?php echo json_encode($jsonString) ?>);
// Prints out:
// var myJson = JSON.parse("{\"prop\":\"val'ue\"}");
// And results: Object - { prop: "val'ue"}
However, If you are 100% sure the JSON is going to be valid, and don't need the weight of the extra parsing / error checking - you could skip all that extra encoding and just write:
var myJson = <?php echo $jsonString; ?>
Remember, JSON is valid JavaScript syntax for defining objects after all!
According to jsonlint it is valid without escaping the single quote, so this is fine:
{"prop": "val'ue"}
But this is invalid:
{"prop":"val\'ue"}
According to json.org json:
is completely language independent but
uses conventions that are familiar to
programmers of the C-family of
languages, including C, C++, C#, Java,
JavaScript, Perl, Python, and many
others
So it is the language conventions in c-type languages regarding the reverse solidus (\) that means that your example is not valid.
You might try the following, however, it's ugly.
JSON.parse("{\"obj\":\"val'ue\"}");
Or just store the string to a var first. This should not store the literal backslash value and therefore the JSON parser should work.
var str = '{"obj" : "val\'ue"}';
JSON.parse(str);