简体   繁体   English

JS:将字符串转换为对象

[英]JS: convert string into object

I have code 我有代码

data = "{isShowLoginPopup:true,newFavOfferId:1486882}";

I want to convert it into JS object (not in JSON) and use it in this way: 我想将其转换为JS对象(不在JSON中)并以这种方式使用它:

data.newFavOfferId = ...

How can I do this? 我怎样才能做到这一点?

If your source is trusted, the simplest solution is to use eval : 如果您的来源是受信任的,最简单的解决方案是使用eval

data = eval('('+data+')');

If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example). 如果您不信任源,那么最好指定可以使用的内容并手动解析字符串(例如,如果仅具有一个级别的属性,就不难了)。

Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes : 另一个解决方案(取决于您的实际数据)是通过插入缺少的引号将数据更改为JSON:

data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));

just remove the quotes 只需删除引号

data = {
    isShowLoginPopup:true,
    newFavOfferId:1486882
};

Fiddle: http://jsfiddle.net/QpZ4j/ 小提琴: http : //jsfiddle.net/QpZ4j/

just remove quotes "" from the 只需删除引号""

data = "{isShowLoginPopup:true,newFavOfferId:1486882}";

DEMO 演示

Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse() . 从表面上看,这看起来像JSON数据,但格式错误,因此无法直接与JSON.parse() This is because JSON objects require keys to be wrapped in quotes... 这是因为JSON对象需要将键括在引号中...

therefore: 因此:

"{isShowLoginPopup:true,newFavOfferId:1486882}"

as valid JSON should be: 有效的JSON应该是:

"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"

So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. 因此,您实际上拥有的是JavaScript对象,而不是JSON,但是您遇到的问题是,这是一个JavaScript对象,它是字符串文字。 If this is hard coded, then you need to just remove the " from the beginning and end of the string. 如果此代码是硬编码的,则只需从字符串的开头和结尾删除"

var data = {isShowLoginPopup:true,newFavOfferId:1486882};

If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object. 如果此对象已序列化并需要从服务器传输到服务器等,那么实际上,它需要作为JSON格式的字符串传输,然后可以反序列化回JavaScript对象。

var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM