简体   繁体   中英

How do I create an object from an object literal in string form?

In JavaScript, I can create an object like this:

var Obj = {someName:"My Name",someNumber:43};

I'm trying to do something like this ( JSFiddle ):

var str = '{someName:"My Name",someNumber:43}';
var Obj = new Object(str);
document.getElementById("result").innerHTML = 'Name: '+Obj.someName;

But the result will be "Name: undefined" . Instead of read the notation, it crates an object with a enumerated object for each char of the string. Why? Is there a way to create an object through a description in a string?

I don't want to use the JSON format as JSON requires the use of double quotes with every property name, which is quite painful to type so often, not good to view and results in a bigger string. If possible, I wish to work with JavaScript object literal notation.

EDIT 2: this is what I'll be working on (with more time). It works for one level object, I'll think about how to make it work recursively in order to convert multidimensional objects or arrays. This question is closed so… good luck for you!

Object.defineProperty(String.prototype, "isObject", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(){
        var string = this;
        if(string.length<=1) return false;
        return (string.charAt(0)=="{" && string.charAt(string.length-1)=="}");
    }
});
Object.defineProperty(String.prototype, "isArray", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(){
        var string = this;
        if(string.length<=1) return false;
        return (string.charAt(0)=="[" && string.charAt(string.length-1)=="]");
    }
});
Object.defineProperty(String.prototype, "toObject", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(){
        var string = this;
        if(!string.isObject() && !string.isArray()) return false;
        var object = string.isObject();
        string = string.slice(1,-1);
        var Obj = (object)? new Object() : new Array() ;
        var Termos = string.split(",");
        var i, Elems, n=0, val;
        for(i in Termos){
            Elems = Termos[i].split(":");
            if(Elems.length==1) {
                val = Elems[0];
                if(object){
                    Obj[n] = val;
                } else {
                    Obj.push(val);
                }
                n++;
            } else {
                if(Elems[1].isObject() || Elems[1].isArray()){
                    val = Elems[1].toObject();
                } else if(typeof(Elems[1])=="number") {
                    val = Elems[1];
                } else {
                    Elems[1] = Elems[1].replace(/['"]+/g, '');
                    val = Elems[1];
                }
                if(object){
                    Obj[Elems[0]] = val;
                } else {
                    Obj.push(val);
                }
            }
        }
        return Obj;
    }
});

You can use

var str = '{someName:"My Name",someNumber:43}';

var strToParse = str.replace("{","").replace("}","").split(",");
for(var i = 0;i < strToParse.length;i++){strToParse[i] = '\"'+strToParse[i].split(":")[0]+'\":'+strToParse[i].split(":")[1];}

strToParse="{"+strToParse+"}";
var Obj = JSON.parse(strToParse);

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