Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C# object to JSON or Javascript object

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?

like image 865
Daebarkee Avatar asked Oct 23 '13 15:10

Daebarkee


2 Answers

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))
like image 192
p.s.w.g Avatar answered Sep 29 '22 20:09

p.s.w.g


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);
like image 40
Andy W Avatar answered Sep 29 '22 19:09

Andy W