JSON breaking with quotes - javascript

I am getting a Broken JSON, with quotes inside quotes. I can't convert it, because of the error;
{
"PENDENCIA": "Whatever",
"RESULTADO": "Teste "blabla"."
}

What you're looking for is how to "escape" characters in JSON. Because JSON uses quotes around all of the string values ("Whatever"), you can't just include a quote inside your string -- there's no way JSON can figure out that "Teste " isn't the full string but instead should be continued until the final ".
You will need to rewrite the JSON to be "Teste \"blabla\"."
If the JSON is being automatically generated, you'll need to fix whatever is generating your JSON.

Related

How to pass multiple double quotes in JSON?

I should construct and pass following text in my JSON scheme. Here is how it should look:
r"""any-text-goes-here"""
Here is how I decided to construct it:
function make(text) {
return `r"""${text}"""`;
}
The function above takes any string and converts it to desired format. But, when I return it in my API as one of fields of JSON, it looks like following:
"r\"\"\"any-text-goes-here\"\"\""
I want to avoid backslashes. I understand that those slashes is needed by Javascript to properly work, but can I remove them, because client side awaits how I described above. Is it possible technically? How can I solve problem?
JSON strings are delimited by " characters.
" characters can be included in a JSON string only by using an escape sequence.
Escape sequences start with a \.
You can't avoid the backslashes.
See the grammar from the JSON website:

JavaScript parse nested string to JSON.parse()

am facing an issue related to Json parsing in JavaScript. I have a string like below which I need to parse inside JSON.parse()
let object = "{ "result": "resultValue", "content": "the content for the content key will "go" here" }"
Now, when am doing like JSON.parse(object)
It throws an error Unexpected token , at some index, because of nested double quotes in content value, could you please suggest how can I parse these type of string to json , thanks in advance.
Change the quotes around the JSON to single quotes, so they don't conflict with the double quotes inside the JSON. And escape the quotes around "go" inside the content string.
If you create the JSON with a proper JSON encoder (e.g. JSON.stringify() in Javascript, json_encode() in PHP) you shouldn't have problems like this.
let object = '{ "result": "resultValue", "content": "the content for the content key will \\"go\\" here" }'
console.log(JSON.parse(object));

How to parse a regex text with Json

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.

How do I replace double quotes with its escape?

var string = "{ "Name": ""Jack"" }"
I want to replace the double quotes with \" so that the variable becomes a valid JSON.
so, it should end up looking like this:
string = "{ "Name": \""Jack"\" }"
I know you can use the replace function but I'm not getting it to work.
Put a backslash in front of each double quote that should be escaped.
var string = "{\"Name\":\"\\\"Jack\\\"\"}"
However, your questions very much looks like an XY problem where you are trying to do something in the completely wrong way! You usually never have to deal with escaping etc. when JSON is involved.
Initially you probably have an object. Let's assume obj = {Name: "Jack"}. Now you apparently want to JSON-encode it. In JavaScript you use JSON.stringify(obj) for it, in PHP you'd do json_encode($obj). However, if you want to assign this to a JS variable, you can just put the encoded JSON right after obj =, like this. If you really have to put a JSON string somewhere, you can simply run the JSON encoder over the string again (that's how I created the string in this post):
JSON.stringify(JSON.stringify({Name: 'Jack'}))

How to deserialize Json object which contain control character using Dojo.fromJson

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

Categories