JavaScript - JSON parsing with carriage and new linear spaces

I use the following JS code to parse a JSON string from a separate JS file:

// extract JSON from a module JS var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/\*\]JSON\*\// ); data = JSON.parse( jsonMatch ? jsonMatch[1] : data ); 

This is an example JS file. I am extracting a JSON string from:

 JsonString = /*JSON[*/{"entities":[{"type":"EntityPlayer","x":88,"y":138}]}/*]JSON*/; 

This code works very well, however if the JS file with the JSON string contains a carriage return and is not on the same full line, I get a syntax error.

Example:

 JsonString = /*JSON[*/{ "entities":[{ "type":"EntityPlayer", "x":88, "y":138}] }/*]JSON*/; 

It returns the following error:

 JSON.parse: unexpected non-whitespace character after JSON data 

Any idea how I could modify my parsing to work by removing extra spaces or to remove carriage returns and new line spaces?

+4
source share
2 answers
 data = JSON.parse( (jsonMatch ? jsonMatch[1] : data).replace(/\n/g,"") ); 
+5
source

Not tested, 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 )

-1
source

All Articles