Parse Complex Json String - javascript

I'm attempting to parse the following JSON string (not in control of the format, I know it's hideous).
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
obj = JSON.parse(json);
I'm getting Error: Unexpected token w in JSON at position 43 which is where the first value of nestedjsonstr begins. Is there any elegant way to parse this?

Maybe this can help you out. You replace the curly braces inside your string without the ", and remove the \.
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
json = json.replace('\"{', '{').replace('}\"', '}').replace('\\"', '"');
obj = JSON.parse(json);
console.log(obj);

Related

Serialize for JavaScript apex

I need to serialize some simple object from .NET to JavaScript...
But I've some problem with apex...
C# example
var obj = new { id = 0, label = #"some ""important"" text" };
string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(obj,
new Newtonsoft.Json.JsonSerializerSettings()
{
StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml
});
JavaScript example
var resJson1= JSON.parse('{"id":0,"label":"some \"important\" text"}');
var resJson2= JSON.parse('{"id":0,"label":"some \u0022important\u0022 text"}');
Both parse give me the same error
VM517:1 Uncaught SyntaxError: Unexpected token I in JSON at position
23 at JSON.parse(<anonymous>)
Where am I wrong?
You're pasting the generated string of JSON into a JavaScript string constant without escaping it further. Try
console.log('{"id":0,"label":"some \"important\" text"}');
You'll see {"id":0,"label":"some "important" text"} i.e. the "important" quotes are no longer escaped by backslashes. (And you'll get the same for your \u0022 example too.) If you want to paste in the backslashes you'll have to escape them again:
var resJson1= JSON.parse('{"id":0,"label":"some \\"important\\" text"}');
The JSON you've generated with a single backslash would be fine if read from a file or URL, just not pasted into JavaScript as a string constant.

How to make string campatible for JSON.parse()

In my application when I enter value as my"name in text field the framework makes a String like (this i can not control):
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
Now this String is passed to JSON.parse() method which produces an error because of ambiguous name field as
\"name\":\"my\"name\"
var str = JSON.parse("[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]")
This results in JSON exception
Is there anything I can do with the string:
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
To escape double quote character in my " name as my \" name to make it valid for JSON.parse method.
I can not control JSON String, I am just passing name as my"name and framework creates a String which is passed to JSON.parse()
I went through a series of text replace. You can try this:
var str = "[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]";
JSON.parse(
str.replace(/\\/i,"").
replace(/{"/g,"{'").
replace(/":"/g,"':'").
replace(/","/g,"','").
replace(/"}/g,"'}").
replace(/'/g,"\###").
replace(/"/g,"\\\"").
replace(/###/g,"\"")
);
It will give back your desired JSON array
var str = "[{\"id\":\"201500000001002\"}]";
str.replace("\"*","\\\"");
var obj = JSON.parse(str);

Convert string from regexp match into object

I have the following string:
var str = 'jfkdjffddf{aaa:12,bbb:25}kfdjf';
And I want to fetch the object from it:
var objStr = str.match('/{(.*?)}/')[1]; // aaa:12,bbb:25
Now I want to use this fetched string as an object:
var obj = JSON.parse('{' + objStr + '}');
Do some operations on it, convert to string back again and replace in the initial text.
The problem is I get unexpected token a on 1 line in my script, the problem is thus probably JSON.parse.
What's the problem, and how can I solve this?

How to convert a string value to Json

I receive a string in the format given below (with double quotes around it):
"'{ "param" : "value"}'"
How can I convert this string into json object so that I could use it as
alert(obj.param)
Thank you
Edit
As I mentioned in above the string has double quotes around it. Here is an example of how I get this string
CSHTML
#{
var prop = "{ \"param\" : \"value\"}";
<a data-type="#prop"></a>
}
and in JS I have this
var obj = anchor.data('type');
I want to be able to use obj.param, how do I achieve this?
Thanks
Use JSON.parse it parses a string as a JSON
var obj = JSON.parse(json);

JavaScript - Parsing JSON with carriage and new line spaces

I am using the following JS code to parse a JSON string from a separate JS file:
// extract JSON from a module's JS
var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/\*\]JSON\*\// );
data = JSON.parse( jsonMatch ? jsonMatch[1] : data );
This is an example of the JS file I extract the JSON string from:
JsonString = /*JSON[*/{"entities":[{"type":"EntityPlayer","x":88,"y":138}]}/*]JSON*/;
This code works just fine, however if the JS file with the JSON string contains carriage returns and isn't on one complete line then I get a syntax error.
Example:
JsonString = /*JSON[*/{
"entities":[{
"type":"EntityPlayer",
"x":88,
"y":138}]
}/*]JSON*/;
Returns the following error:
JSON.parse: unexpected non-whitespace character after JSON data
Any idea how I could modify my parsing to work by either stripping out whitespace or to remove carriage returns and new line spaces?
data = JSON.parse( (jsonMatch ? jsonMatch[1] : data).replace(/\n/g,"") );
Did not test it, but maybe this is what you are looking for?
var JsonString = JsonString.replace(new RegExp( "\\n", "g" ),"");
(from http://www.bennadel.com/blog/161-Ask-Ben-Javascript-Replace-And-Multiple-Lines-Line-Breaks.htm)

Categories