所以我想创建这个JSON对象:
{
"id":"3",
"created":"0000-00-00",
"parentIDs":null,
"childIDs":"",
"uid":"movies",
"title":"Movies",
"related":"movies",
"pos":"",
"css":"{ "background-image":"-webkit-linear-gradient(bottom, rgb(46,44,46) 49%, rgb(18,17,18) 75%)" }"
}
来自字符串:
value = ""id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":"""
这个字符串来自一个数据库,所以我无法真正改变格式,但它应该是这样的。
(这个字符串来自一个类似的字符串数组,我迭代它们,不知何故丢失它们周围的{}
我尝试用value.substr(1, value.length - 2);
删除外部引号。然后使用.toJSON();
转换它,但它只添加了许多我不需要的额外斜杠。
我只需要在其周围添加{}
,然后javascript就会将其视为JSON对象。
有没有这样做的简写方法?或者是否有一个小型库可以巧妙地将我凌乱的字符串转换为JSON对象?
[update]
我试过了:eval('{' + value + '}');
但我在Chrome中获得了Uncaught SyntaxError: Unexpected token :
。
我在Chrome和Firefox中尝试过JSON.parse但得到:TypeError: JSON.parse is not a function
,它必须是字符串的格式。我开始怀疑“css”条目,虽然它在第一个“id”条目开始抱怨,它期待一个函数而不是JSON?
(我减少了原始JSON,但忘记了最重要的“css”)
[UPDATE2]
好的,所以我将css数据改为'
而不是"
,现在它实际上会解析,但现在我的脚本坏了,因为我期待来自db的原始CSS,任何将结果'css':'blabla'
更改为:"css":"blabla"
?
答案 0 :(得分:14)
如果您的字符串包含有效的JSON,则可以使用JSON.parse()
将其转换为JavaScript对象。
假设你有一个字符串:
value = '"id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":""';
然后你会这样做:
obj = JSON.parse("{"+value+"}");JSON
请注意,它需要{}
作为字符串的一部分才能成为有效的JSON字符串。
答案 1 :(得分:6)
var value = '"id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":"","css":"{ "background-image":"-webkit-linear-gradient(bottom, rgb(46,44,46) 49%, rgb(18,17,18) 75%)" }"';
var nestedObjects = [];
String.prototype.trimQuotes = function () {
return this.indexOf('"') === this.lastIndexOf('"') ? this.substring(this.indexOf('"') + 1) : this.substring(this.indexOf('"') + 1, this.lastIndexOf('"'));
};
function convertObject(str) {
var retObj = {};
$.each(str.split(','), function () {
var keypair = this.split(':');
if (keypair.length < 2) { return; }
retObj[keypair[0].trimQuotes().trim()] = keypair[1].indexOf('@') > -1 ? nestedObjects[parseInt(keypair[1].trimQuotes().substring(1), 10)].trimQuotes().trim() : keypair[1].trimQuotes();
});
return retObj;
}
var temp = value.split('{')[0];
$.each(value.split('{'), function (i, t) {
if (i === 0) {
return;
}
var splits = t.split('}');
nestedObjects.push(splits[0]);
temp += '@' + (i - 1);
if (splits.length > 1) {
temp += splits[1];
}
});
答案 2 :(得分:4)
它是jquery
中的inbuild选项,用于将字符串解析为Json。
as
var str = '{ "id":"3", "created":"0000-00-00", "parentIDs":null, "childIDs":"", "uid":"movies", "title":"Movies", "related":"movies", "pos":"", "css":"{ background-image:-webkit-linear-gradient(bottom, rgb(46,44,46) 49%, rgb(18,17,18) 75%) }"}';
$(document).ready(function () {
var result = jQuery.parseJSON(str);
console.log(result);
});
从CSS部分中删除了"
这是输出
请参阅以下网址http://api.jquery.com/jQuery.parseJSON/
答案 3 :(得分:3)
这是一个使用正则表达式的解析器!
var tmp = '"id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":"","css":"{ "background-image":"-webkit-linear-gradient(bottom, rgb(46,44,46) 49%, rgb(18,17,18) 75%)" }"' ;
var reg = /"(\w+)":(?:"([\w-]*)"|"{([^}]*)}"|(null))/g;
var obj ={};
tmp.replace(reg,function(text,all,dall,hall,vall){
obj[all]=hall||dall||vall;
console.log(all +":"+obj[all]);
});
这很简单不是吗?
答案 4 :(得分:2)
如果你说你的字符串没有解析的原因是因为你的JSON数组的下一个维度用引号括起来,这里有一个解决方法。我确信有更好的方法。
var value = '"id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":"","css":"{ "background-image":"-webkit-linear-gradient(bottom, rgb(46,44,46) 49%, rgb(18,17,18) 75%)" }"';
value = value.replace("\"{", "{");
value = value.replace("}\"", "}");
value = "{"+value+"}";
value = JSON.parse(value);
console.log(value);
这是我的fiddle
答案 5 :(得分:2)
正如大家已经提到的那样jQuery.parseJSON()
就是这样。在你的情况下,你需要首先清理从SQL获得的字符串,否则你将无法解析为正确的json:
// format from SQL : value = "validJSON"
var fromSQL = 'value = ""id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":"""';
// we need to remove @value ="' at the beginnig and '"' at the end
var withoutWrapper = fromSQL.substring(('value = "').length, fromSQL.length-1);
// now add {} to make it as a json obj
var withNewWrapper = '{' +withoutWrapper +'}';
// parse it
var json= jQuery.parseJSON(withNewWrapper);
以下是功能示例:http://jsfiddle.net/vojtiik/pzJTa/
此JsonViewer之类的工具总能提供帮助!
答案 6 :(得分:0)
您要找的是JSON.parse
:
var str = '{"id":"3",
"created":"0000-00-00",
"parentIDs":null,
"childIDs":"",
"uid":"movies",
"title":"Movies",
"related":"movies",
"pos":""}',
foo = JSON.parse(str);
它当然看起来更干净。
答案 7 :(得分:0)
这个怎么样
var arr = new Function('return {' + value + '}')();
根据您的要求,eval
和JSON.parse更安全,更快速。
答案 8 :(得分:0)
据我所知,您没有使用AJAX接收此字符串,而是将其直接嵌入到服务器端的某些脚本中 - 因此无需在客户端解析它(此处不需要JSON.parse)。您所需要的只是根据JSON规则正确编写对象数据:
var data_object = {
"id":"3",
"created":"0000-00-00",
"parentIDs":null,
"childIDs":"",
"uid":"movies",
"title":"Movies",
"related":"movies",
"pos":"",
"css":'{ "background-image":"-webkit-linear-gradient(bottom, rgb(46,44,46) 49%, rgb(18,17,18) 75%)" }'
}
注意css属性(如果你想在字符串中包含引号,你可以简单地使用不同的引号来标记字符串的开头和结尾)。没有其他方法 - 你只需要正确引用你的字符串常量。