2

I hit a problem with JSON. I want to pass serialized object to a JSON.parse method in JS. Everything works fine until one of string values does not have quotes, like for example HTML code. Then you get JSON parse error in JS.

Simply I get:

var test = JSON.parse('{"test":"<p>Terms <a href=\"google.pl\"></a></p>"}');

But what works is:

var test = JSON.parse('{"test":"<p>Terms <a href=\\"google.pl\\"></a></p>"}');

Here is my test view code, any thoughts? How to pass this object properly?

@{
    Layout = null;
}

@{
    string args = Newtonsoft.Json.JsonConvert.SerializeObject(new
    {
        test = @"<p>Terms <a href=""google.pl""></a></p>"
    }, new Newtonsoft.Json.JsonSerializerSettings
    {
        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
    });
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script>
        var test = JSON.parse('@Html.Raw(args)');
    </script>
    <div> 
    </div>
</body>
</html>
5
  • What is the actual question? Also i think it should be var test = JSON.parse(@Html.Raw(args).ToString()); instead of var test = JSON.parse('@Html.Raw(args)');... Commented Dec 5, 2017 at 11:02
  • Nope. ToString breaks it even more as it HTML encodes it. Question is how to pass this object to successfully deserialize on JS side. Commented Dec 5, 2017 at 11:11
  • Your example is incomplete, some view code is missing. Commented Dec 5, 2017 at 11:19
  • This is the whole razor view code. What is missing? Commented Dec 5, 2017 at 11:22
  • @mzdieg I didn't understand the question, i thought something with test is the issue. Nevermind... Commented Dec 5, 2017 at 11:39

1 Answer 1

4

You don't need to parse it, as it is already a JSON object. Just use:

<script>
    var test = @Html.Raw(args);
</script>

JSON.parse is used to parse string to object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.