I am a C# developer and a newbi in Javascript. I have one C# object and finally, in index.cshtml, I can get a string converted from the object via calling Json.Encode(obj)
The string is:
[
{
"Name":"CASE_A",
"Values":[99.8,99.9,99.9,99.8,99.8,96.3,22.3]
},
{
"Name":"CASE_B",
"Values":[99.8,99.8,99.8,96.3,22.3]
},
]
However, when I call JSON.parse(@TheString),I got:
Uncaught SyntaxError: Unexpected token &
The location of this error shows me this:
data = JSON.parse([{"Name":"CASE_A","Values":[99.8,99.9,99.9,99.8 ....
How can I fix this problem?
Thank you for the answers! But still I got an error:
Uncaught SyntaxError: Unexpected token o
For simple testing, I used this:
@{
string tmp = "[{\"Name\":\"CASE_A\",\"Values\":[99.8,99.9,98.6]},{\"Name\":\"CASE_B\",\"Values\":[96.7,11.1]}]";
}
var data1 = JSON.parse(@Html.Raw(@tmp));
And source shows this line:
var data1 = JSON.parse([{"Name":"CASE_A","Values":[99.8,99.9,98.6]},{"Name":"CASE_B","Values":[96.7,11.1]}]);
I cannot see any "o" here.
Also, for making javascript object, Travis suggested to remove the key name before serialization. But in C#, all object must have its member name. All I can think of is string manipulation. Is there any better way to do so?
Razor will automatically escape HTML entities for you in an attempt to be helpful. You can disable this with Html.Raw
:
JSON.parse(@Html.Raw(TheString))
For your second error, JSON.parse expects a string, but you are passing in an array. Your outputted js code has to look like this to work:
var data1 = JSON.parse("[{\"Name\":\"CASE_A\",\"Values\":[99.8,99.9,98.6]},{\"Name\":\"CASE_B\",\"Values\":[96.7,11.1]}]");
I also want to note that since you are injecting this object into your javascript code on the server side, there is no need to call JSON.parse at all. As long as you send properly formatted javascript to the client where it will be evaluated and run, then it doesn't matter how it's created on the server. Try this instead:
var data1 = @Html.Raw(@tmp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With