JavaScript - Parsing JSON with carriage and new line spaces

10,551
data = JSON.parse( (jsonMatch ? jsonMatch[1] : data).replace(/\n/g,"") );
Share:
10,551
fulvio
Author by

fulvio

Updated on July 10, 2022

Comments

  • fulvio
    fulvio almost 2 years

    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?

  • ThiefMaster
    ThiefMaster almost 12 years
    Whitespace is perfectly valid in a JSON string.
  • DerApe
    DerApe almost 12 years
    Okay, sorry I understood the question in a wrong way. Though it's more or less java string replacement.
  • fulvio
    fulvio almost 12 years
    I'll accept this answer, however the following was actually an issue where I wasn't closing a StreamReader object in my C# code.