将无效的JSON字符串转换为JSON [英] convert invalid JSON string to JSON

查看:164
本文介绍了将无效的JSON字符串转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无效的json字符串,如下所示,

I have an invalid json string like following,

"{one: 'one', two: 'two'}"

我试图使用JSON.parse将其转换为对象。但是,这不是有效的json字符串。
是否有任何函数可以将这种无效格式转换为有效的json字符串或直接转换为对象?

I tried to use JSON.parse to convert it to an object. however, this is not valid json string. Is there any functions can convert this invalid format into a valid json string or directly convert into an object?

推荐答案

如果您的示例语法与您的真实JSON相同,则JSONLint表示您需要双重引用名称和值。

IF your example syntax is the same as your real JSON, JSONLint says you need double quote for the name AND the value.

仅在这种情况下,请使用以下替换调用:

In this case only, use these replace calls:

var jsontemp = yourjson.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
//yourjson = "{one: 'one', two: 'two'}"
//jsontemp = "{"one": 'one', "two": 'two'}"
//correctjson = "{"one": "one", "two": "two"}"

但是你应该首先尝试使用有效的Json。

However you should try to work with a valid Json in the first place.

这篇关于将无效的JSON字符串转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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