解析“轻松"没有 eval 的 JSON [英] Parsing "relaxed" JSON without eval

查看:19
本文介绍了解析“轻松"没有 eval 的 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解析轻松"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 :-)

推荐答案

您可以使用正则表达式替换来清理 JSON:

You could sanitize the JSON using a regular expression replace:

var badJson = "{muh: 2}";
var correctJson = badJson.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": ');
JSON.parse(correctJson);

这篇关于解析“轻松"没有 eval 的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆