JavaScript - 用回车和换行符解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11027938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:51:48  来源:igfitidea点击:

JavaScript - Parsing JSON with carriage and new line spaces

javascriptjqueryjsonparsing

提问by fulvio

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

我正在使用以下 JS 代码从单独的 JS 文件中解析 JSON 字符串:

// 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:

这是我从中提取 JSON 字符串的 JS 文件示例:

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.

这段代码工作得很好,但是如果带有 JSON 字符串的 JS 文件包含回车并且不在一个完整的行上,那么我会收到语法错误。

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?

知道如何通过删除空格或删除回车符和换行符来修改我的解析以使其工作吗?

回答by jornare

data = JSON.parse( (jsonMatch ? jsonMatch[1] : data).replace(/\n/g,"") );

回答by DerApe

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)

(来自http://www.bennadel.com/blog/161-Ask-Ben-Javascript-Replace-And-Multiple-Lines-Line-Breaks.htm