jQuery 从字符串创建 JSON,用作对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18232075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:14:57  来源:igfitidea点击:

Create JSON from string, to use as object

jqueryjson

提问by TrySpace

So I want to create this JSON object:

所以我想创建这个 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%)" }"
}

from string:

从字符串:

value = ""id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":"""

This string comes from a database, so I can't really change the formatting, but it should be correct like this.

这个字符串来自数据库,所以我不能真正改变格式,但它应该像这样正确。

(This string originates from an array of similiar strings, which I iterate through, somehow losing the {} around them)

(此字符串源自一组相似的字符串,我对其进行迭代,不知何故丢失了它们周围的 {})

I tried removing the outer quotes with value.substr(1, value.length - 2);. And then convert it with .toJSON();but it only adds a whole lot of extra slashes I don't need.

我尝试用value.substr(1, value.length - 2);. 然后使用.toJSON();它进行转换,但它只会添加很多我不需要的额外斜线。

I just need to add {}around it, and then javascript would see it as a JSON object.

我只需要{}在它周围添加,然后 javascript 就会将它视为一个 JSON 对象。

Is there any shorthand way of doing that? or is there a small library that can convert my messy string in a clever way to a JSON object?

有没有什么速记方法可以做到这一点?或者是否有一个小型库可以巧妙地将我凌乱的字符串转换为 JSON 对象?

[update]

I tried: eval('{' + value + '}');But i get Uncaught SyntaxError: Unexpected token :in Chrome.

我试过:eval('{' + value + '}');但我进入Uncaught SyntaxError: Unexpected token :了 Chrome。

I tried JSON.parse but get: TypeError: JSON.parse is not a functionin Chrome and Firefox, it must be the string's formatting. I'm beginning to suspect the "css" entry, although it starts complaining at the first "id" entry, it's expecting a function instead of JSON?

我试过 JSON.parse 但得到:TypeError: JSON.parse is not a function在 Chrome 和 Firefox 中,它必须是字符串的格式。我开始怀疑“css”条目,尽管它在第一个“id”条目处开始抱怨,但它期待的是一个函数而不是 JSON?

(I cut down the raw JSON, but forgot the most important "css" one)

(我删减了原始 JSON,但忘记了最重要的“css”)

[update2]

[更新2]

Ok, so I changed the css data to 'instead of ", now it will actually parse, but now my script is broken, because I'm expecting raw CSS from the db, any way to change the resulting 'css':'blabla'to: "css":"blabla"?

好的,所以我将 css 数据改为'而不是",现在它实际上会解析,但现在我的脚本坏了,因为我期待来自数据库的原始 CSS,有什么方法可以将结果更改'css':'blabla'为:"css":"blabla"

回答by knolleary

If you have a string that contains valid JSON, you can convert it to a JavaScript Object using JSON.parse().

如果您有一个包含有效 JSON 的字符串,您可以使用JSON.parse().

Assuming you have a string:

假设你有一个字符串:

value = '"id":"3","created":"0000-00-00","parentIDs":null,"childIDs":"","uid":"imdb","title":"Imdb","related":"movies","pos":""';

you would then do:

然后你会这样做:

obj = JSON.parse("{"+value+"}");JSON

Note it needs the {}as part of the string to be a valid JSON string.

请注意,它需要{}作为字符串的一部分是有效的 JSON 字符串。

回答by Neil S

ok, so this is the best I could come up with:

好的,这是我能想到的最好的方法:

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];
    }
});

http://jsfiddle.net/SkCVd/5/

http://jsfiddle.net/SkCVd/5/

回答by Bhaarat

It's inbuild option in jqueryto parse string into Json.

jquery将字符串解析为 Json是 inbuild 选项。

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);
    });

removed "from CSS portion
Here is output enter image description hererefer below url http://api.jquery.com/jQuery.parseJSON/

"从 CSS 部分删除
这里是输出 在此处输入图片说明参考下面的网址http://api.jquery.com/jQuery.parseJSON/

回答by AhmadF

here is a parser using regx!

这是一个使用 regx 的解析器!

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]);
});

its quite simple isn't it?

它很简单,不是吗?

回答by Joe Buckle

Here is a bit of a workaround if you say the reason your string isn't parsing is because the next dimension of your JSON array is wrapped in quotes. I'm sure there is a better way though.

如果您说您的字符串未解析的原因是 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);

And here is my fiddle

这是我的小提琴

回答by Vojtiik

As everyone already mentioned jQuery.parseJSON()is the way. In your case you need to clean up the string you getting from SQL first, otherwise you won't be able to parse into correct json:

正如每个人已经提到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); 

Here is functional example : http://jsfiddle.net/vojtiik/pzJTa/

这是功能示例:http: //jsfiddle.net/vojtiik/pzJTa/

Tools such as this JsonVieweralways helps !

像这个JsonViewer这样的工具总是有帮助的!

回答by VitaliyG

As I understand you are not receiving this string with AJAX, but embedding it directly in some script on server side - so there is no need to parse it at client(JSON.parse is not needed here). All you need is to correctly write object data according JSON rules:

据我了解,您没有使用 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%)" }'

}

Pay attention to css property (if you want to include quotes in string you can simply use different quotes for marking begin and end of the string). There is not other way - you just have to properly quote your string constants.

注意 css 属性(如果你想在字符串中包含引号,你可以简单地使用不同的引号来标记字符串的开头和结尾)。没有其他方法 - 您只需要正确引用您的字符串常量。

回答by federico-t

What you're looking for is JSON.parse:

你要找的是JSON.parse

var str = '{"id":"3",
"created":"0000-00-00",
"parentIDs":null,
"childIDs":"",
"uid":"movies",
"title":"Movies",
"related":"movies",
"pos":""}',
    foo = JSON.parse(str);

It could certainly look cleaner though.

不过,它当然可以看起来更干净。

回答by Exception

How about this

这个怎么样

  var arr = new Function('return {' + value + '}')();

This is safer and faster equivalent for evaland JSON.parse for your requirement.

eval对于您的要求,这对JSON.parse来说更安全、更快捷。