Uriil
Uriil

Reputation: 12628

.NET create JSON object, where value contains quotes

I am using Newtonsoft.Json to generate JSON object:

JObject testObject = new JObject();
testObject["key"] = "\"value\"";
var result = testObject.ToString();
Console.WriteLine(result);

Result of this operation is: { "key": "\"value\"" }

But, when I try parse it using JS:

var data = JSON.parse( '{ "key": "\"value\"" }' );

I am getting error: Uncaught SyntaxError: Unexpected token v in JSON at position 11

If I manually change json to: { "key": "\\"value\\"" }, it parses it correctly. However, i can not generate it from .NET.

Am I missing something?

Upvotes: 0

Views: 68

Answers (1)

JLRishe
JLRishe

Reputation: 101738

Am I missing something?

What you're missing is that you tried to copy your JSON into a JavaScript string literal, but you didn't correctly escape it.

If you want to put the JSON { "key": "\"value\"" } into a string literal, this value contains backslashes, so you would have to escape them:

var data = JSON.parse( '{ "key": "\\"value\\"" }' );

This is exactly what you found to work correctly.

If you try to run the line you had:

var data = JSON.parse( '{ "key": "\"value\"" }' );

That string literal evaluates to the value { "key": ""value"" }, which is not the same as the JSON that Newtonsoft produced and is not valid JSON.

The bottom line: It looks like you've generated some valid JSON with a library, but then you tried to copy it by hand and created an error in the process of doing so. Perhaps this was just for experimentation, but you should set up a pathway for the JSON to pass from Newtonsoft to your JavaScript without human intervention. This should prevent such issues like the one you had.

Upvotes: 2

Related Questions