简体   繁体   中英

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:

data.newFavOfferId = ...

How can I do this?

If your source is trusted, the simplest solution is to use 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 :

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

just remove the quotes

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

Fiddle: 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() . This is because JSON objects require keys to be wrapped in quotes...

therefore:

"{isShowLoginPopup:true,newFavOfferId:1486882}"

as valid JSON should be:

"{\"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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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