How to parse a regex text with Json - javascript

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.

Related

Not able to convert string to JSON in Javascript

I've a string in JSON format. I'm trying to iterate it. I have validate the string whether its JSON or not. It is fine. But, when I try to iterate it, it throws me error .
Here is my
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":"{\"color\": \"blue\",\"value\": \"#f00\"}"},{"id":8,"userId":"123","courseId":"C5","courseValue":"{\"color\": \"green\",\"value\": \"#f00\"}"}]';
Here is the fiddle
http://jsfiddle.net/hLkUz/40/
You have taken some JSON and wrapped ' around it to try to make it a JavaScript string literal.
Some characters have special meaning in JavaScript string literals (such as \ which starts an escape sequence). You have failed to escape them within the string.
Consequently, to take an example:
"{\"color\":…
… when parsed as part of the JavaScript string literal becomes:
"{"color":…
… which isn't valid JSON.
You need to escape the special characters for the JavaScript string literal.
Better yet, restructure your JSON so that it doesn't contain values which are encoded as JSON themselves. Use an object instead of a string containing JSON representing an object.
You are having unwanted double string in values. Corrected json string is here
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{\"color\": \"blue\",\"value\": \"#f00\"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{\"color\": \"green\",\"value\": \"#f00\"}}]';
Try this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
There's no need to wrap the object with " nor escape it.
What you need is this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
Fiddle
I'm not sure if you intend to escape the JSON within courseValue. However it seems like the escaping of the nested objects is the problem. This works
http://jsbin.com/mekiwalidu/edit?js,console,output
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
var obj = JSON.parse(string);
console.log(obj);

Why can't Javascript parse this JSON array from a string literal?

What I am trying to do is simple. Parse this array holding json objects into a Javascript array.
var merchantsJson = JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]');
But the unicode character \u003C seems to be breaking the parser. In the chrome console I see "Uncaught SyntaxError: Unexpected token <"
A little more info. The above is what the code is evaluated to. In reality the code contains a jsp expression.
var merchantsJson = JSON.parse('${jsonArr}');
If I remove the single quotes, there is no issue, but eclipse give me an "missing semicolon" error message. Is it possible to parse the array with the quotes as I am trying to do?
The interpolation of ${jsonArr} is already a JavaScript object. When you wrap it in '${jsonArr}' this turns it into a string and you have to use JSON.parse.
There's no need to make it a string. You can just do var merchantsArray = ${jsonArr}. JSON constructs are already interoperable with JavaScript code.
Because there's an extra " in your string literal that is encoded by \u0022:
> '[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]'
[{"id":61693,"name":"Más"},{"id":61690,"name":"'"</div>"}]
In short, your JSON in the string is invalid. You would need to escape the unicode escape sequences for the quotes in the string literal ("'\u0022</div>"), by using
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\u0022\u003C/div\u003E"}]'
// ^
or escape the quote character ("'\"</div>"):
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\\u0022\u003C/div\u003E"}]');
// ^^
However, there actually is no need to use JSON at all. Just output a JS array literal into your code:
var merchantsJson = ${jsonArr};
Try to replace \u with \\u. If you don't, JSON parser receives already decoded Unicode, which created polluted JSON.
It's not because of \u003C, rather the \u0022 character is causing the issue, since it's a quotation mark and JavaScript treats it literally ending the string.
You need to escape that character: \\u0022 .
you have to use special character in your JSON string, you can escape it using \ character.
you need to replace \ with \\.
[{\"id\":61693,\"name\":\"Más\"},{\"id\":61690,\"name\":\"\\u0027\\u0022\\u003C/div\\u003E\"}]

How to remove unwanted encoding symbols in json

I have json on my page coming from the string property of the model:
var myJson = '[{\"A\":1,\"B\":10,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"},
{\"A\":1,\"B\":11,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"}]'
I want to process that json via javascript on the page
I am doing $.parseJSON(#Html.Raw(Json.Encode(myJason))); but json still contain \" symbol. If i do $.parseJSON(#Html.Raw(Json.Decode(myJason))); it is just producing an $.parseJSON(System.Web.Helpers.DynamicJsonArray); How can I fix that?
Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of ("\").
var myString = JSON.stringify(myJson);
var myNewString = myString.replace(/\\/g, "");
Hope this helps.
There are two ways
1 from where you get the JSON asked them to send you as url encoded format. at your end you need to decode url and you will get the Perfect JSON.
Other wise do the laborious replace method for each and every special charecter with respective char.
like above example you need to use replace("\","");
There is no JSON parser that will be able to deal with a JSON string that isn't properly formatted in the first place.
so you need to make sure that your theModel is formatted appropriately and according JSON.org standards.
Like
Koushik say you can use String operation

Javascript .replace() of the character " with the characters \"

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\"}"

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