转换将对象字符串转换为JSON或Object [英] convert "converted" object string to JSON or Object
问题描述
自从我升级了我的prototypeJS框架以来,我一直在关注以下问题.
i've following problem and since i upgraded my prototypeJS framework.
JSON解析不再能够将该字符串转换为对象.
the JSON parse is not able anymore to convert this string to an object.
"{empty: false, ip: true}"
以前在1.6版中是有可能的,现在它必须是一个经过验证"的JSON字符串,例如
previously in version 1.6 it was possible and now it needs to be a "validated" JSON string like
'{"empty": false, "ip": true}'
但是如何将第一个示例转换回对象?
But how can i convert the 1st example back to an object?
推荐答案
JSON需要所有键都加引号,因此:
JSON needs all keys to be quoted, so this:
"{empty: false, ip: true}"
不是有效的JSON.您需要对其进行预处理,以便能够解析此JSON.
is not a valid JSON. You need to preprocess it in order to be able to parse this JSON.
function preprocessJSON(str) {
return str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g,
function(all, string, strDouble, strSingle, jsonLabel) {
if (jsonLabel) {
return '"' + jsonLabel + '": ';
}
return all;
});
}
(在JSFiddle上尝试)它使用一个简单的正则表达式来替换单词,用冒号表示,该词用双引号引起来.正则表达式不会在其他字符串中引用标签.
(Try on JSFiddle) It uses a simple regular expression to replace a word, followed by colon, with that word quoted inside double quotes. The regular expression will not quote the label inside other strings.
那您就可以放心了
data = JSON.parse(preprocessJSON(json));
这篇关于转换将对象字符串转换为JSON或Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!