解析“放松”没有eval的JSON [英] Parsing "relaxed" JSON without eval
问题描述
解析轻松JSON的最简单方法是什么,但避免邪恶 eval
?
What is the easiest method to parse "relaxed" JSON but avoid evil eval
?
以下抛出错误:
JSON.parse("{muh: 2}");
因为正确的JSON应该引用键: {muh:2}
since proper JSON should have keys quoted: {"muh": 2}
我的用例是一个简单的测试接口,用于将JSON命令写入节点服务器。到目前为止,我只是使用 eval
,因为它只是一个测试应用程序。但是,在整个项目中使用JSHint一直困扰着我 eval
。所以我想要一个安全的选择,仍然允许放宽键的语法。
My use case is a simple test interface I use to write JSON commands to my node server. So far I simply used eval
as it's just a test application anyway. However, using JSHint on the whole project keeps bugging me about that eval
. So I'd like a safe alternative that still allows relaxed syntax for keys.
PS:我不想仅仅为了测试而自己编写解析器申请: - )
PS: I don't want to write a parser myself just for the sake of the test application :-)
推荐答案
您已经知道这一点,因为您在这里提到我 = D,但我认为在这里记录它可能会很好:
You already know this, since you referred me here =D, but I figure it might be good to document it here:
我一直希望能够编写仍然有效的JS轻松JSON,所以我采用了Douglas Crockford的无eval json_parse.js 并将其扩展为支持ES5功能:
I'd long had the same desire to be able to write "relaxed" JSON that was still valid JS, so I took Douglas Crockford's eval-free json_parse.js and extended it to support ES5 features:
https://github.com/aseemk/json5
此模块在npm上可用,可用作原生 JSO的替代品N.parse()
方法。 (它的 stringify()
输出常规JSON。)
This module is available on npm and can be used as a drop-in replacement for the native JSON.parse()
method. (Its stringify()
outputs regular JSON.)
希望这会有所帮助! =)
Hope this helps! =)
这篇关于解析“放松”没有eval的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!