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'}))
Related
I have some Javascript code embedded in some JSON fields.
For example:
{
"elements": [{
"bindingParams": "return field.innerHTML.match(/\\d+/gi).toString();\n"
}]
}
And I want to write this code to a new file. The thing is that when this Javascript is set as a value to a JObject the newlines and other characters as the backslash are being escaped.
I have tried using Regex.Unescape(field.Value<string>()), but I get an error in fields with \\d
The error is parsing 'field.innerHTML.match(/\\d+/gi).toString();' - Unrecognized escape sequence \\d.
I could always go with field.Value<string>().Replace("\\n", "\n).Replace("\\","\").Etc(...) but I don't know the sequences that Newtonsoft JObject is escaping.
I would like to know the escape characters that Newtonsoft uses or a method/function from Newtosoft that allows me to unescape the string.
I appreciate your help. Thanks in advance.
The double backslash "\\d" is causing the problem.
Before parsing the jsonString try to replace them this way:
var jsonString ="{\"elements\": [{\"bindingParams\": \"return field.innerHTML.match(/\\d+/gi).toString();\n\"}]}";
jsonString = jsonString .Replace("\\", "\\\\"); // <=== this line
var o = JObject.Parse(jsonString); // This works !
I found out that the issue was that I was trying to unescape an already unescaped string.
The field.Value<string>() already unescapes the string. So the solution to my issue was just not to call Regex.Unescapeand use the value directly.
Sorry.
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.
I am trying to pass a JSON string to a C# .exe as a command line argument, from Javascript as a node.js child-process. For the sake of argument my JSON looks something like this:
string jsonString = '{"name":"Tim"}'
The issue with passing this as a C# arg is that the double quotation marks must be retained if I hope to parse it in the C# code. As such, what I need to pass into the C# command line needs to look something like this, where I escape the double quotation mark:
string jsonStringEscaped = '{\"name\":\"Tim\"}'
The motivation for doing this is that it allows me to maintain a consistent object structure across the two languages, which is obviously highly desirable for me.
In order to achieve this, I am attempting to use the Javascript .replace() method prior to sending the argument to the C#, and to do this I use a simple RegEx:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\"")
Unfortunately, this returns something of the form '{\\"name\\":\\"Tim\\"}' which is useless to me.
I have tried variations on this:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\ \"")
\\ returns '{\\ "name\\ ":\\ "Tim\\ "}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\\")
\\ returns '{\\\\name\\\\:\\\\Tim\\\\}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\")
\\ is invalid
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\ ")
\\ returns '{\\ name\\ :\\ Tim\\ }'
I have tried variations where the second .replace() argument is contained within single quotation marks '' rather than double quotation marks "" with no success.
Can anyone tell me what I am doing wrong? Better yet, can anyone suggest a more efficient method for doing what I am trying to achieve?
Unless I'm misreading you, I think you're just trying to escape a character that doesn't need to be escaped in your regex (").
var jsonString = '{"name":"Tim"}'
var escaped = jsonString.replace(/"/g, '\\"');
// escaped == "{\"name\":\"Tim\"}"
I want to add JSON data with the following string value:
json = "d:\xyz\abc";
This value is coming from a database at runtime. When I am going to display it in datatable, JSON formatting error is displayed. My requirement is that the above value will be displayed as it is in the datatable. Please help.
Escape it with another \:
var json = "d:\\xyz\\abc";
You'd better use a JSON library for your programming language. You don't retrieve database values directly with jquery, aren't you?
So, you'd use something like JSON.escape(my_string_from_db), or, in Ruby language I usually do my_string.to_json.
This will automatically escape everything that needs to be escaped.
Change to this:
json = "d:\\xyz\\abc";
See this question for further information
\ is the escape character in JavaScript strings, it gives special meaning to the character following the slash. Like \t is a tab character, \n is a new line. To put a backslash literal you'll need to use \\
The first backslash says the next character is going to be special, the following backslash says "oh, it's just a backslash."
Since the JSON format specifies that single quotes should not be escaped, most libraries (or even the native JSON parser) will fail if you have an escaped single quote in it. Now this usually is not a problem since most of the time you do an XHR that fetches some data formatted as JSON and you use the responseText which contains your JSON string that you can then parse, etc.
In this particular situation, I have a JSON string stored in a database as text... so the database contains something like {"property":"value"} and I want to output this as part of an HTML page created by the server so that the JavaScript code in that page looks something like this:
var x = '{"property":"value"}';
Now if the JSON string in the database contains a single quote like this:
{"property":"val'ue"}
Then I need to escape it or else I will never be able to use it as a string:
console.clear();
var obj = {prop:"val'ue"};
var str = JSON.stringify(obj);
console.log("JSON string is %s",str);
console.dir(JSON.parse(str)); //No problem here
//This obviously can't work since the string is closed and it causes an invalid script
//console.dir(JSON.parse('{prop:"val'ue"}'));
//so I need to escape it to use a literal JSON string
console.dir(JSON.parse('{"prop":"val\'ue"}'));
The question then is why {"prop":"val\'ue"} not considered a valid JSON string ?
In JavaScript - the string '{"prop":"val\'ue"}' is a correct way to encode the JSON as a string literal.
As the JavaScript interpreter reads the single-quoted string, it will convert the \' to '. The value of the string is {"prop":"val'ue"} which is valid JSON.
In order to create the invalid JSON string, you would have to write '{"prop":"val\\\'ue"}'
If I understand the question right, you are trying to generate JavaScript code that will set some variable to the decoded version of a JSON string you have stored in the database. So now you are encoding the string again, as the way to get this string into JavaScript is to use a string literal, passing it through JSON.parse(). You can probably rely on using the server side JSON encoder to encode the JSON string as a JavaScript string literal. For instance:
<?php $jsonString = '{"prop":"val\'ue"}'; ?>
var myJson = JSON.parse(<?php echo json_encode($jsonString) ?>);
// Prints out:
// var myJson = JSON.parse("{\"prop\":\"val'ue\"}");
// And results: Object - { prop: "val'ue"}
However, If you are 100% sure the JSON is going to be valid, and don't need the weight of the extra parsing / error checking - you could skip all that extra encoding and just write:
var myJson = <?php echo $jsonString; ?>
Remember, JSON is valid JavaScript syntax for defining objects after all!
According to jsonlint it is valid without escaping the single quote, so this is fine:
{"prop": "val'ue"}
But this is invalid:
{"prop":"val\'ue"}
According to json.org json:
is completely language independent but
uses conventions that are familiar to
programmers of the C-family of
languages, including C, C++, C#, Java,
JavaScript, Perl, Python, and many
others
So it is the language conventions in c-type languages regarding the reverse solidus (\) that means that your example is not valid.
You might try the following, however, it's ugly.
JSON.parse("{\"obj\":\"val'ue\"}");
Or just store the string to a var first. This should not store the literal backslash value and therefore the JSON parser should work.
var str = '{"obj" : "val\'ue"}';
JSON.parse(str);