简体   繁体   English

如何从字符串形式的对象文字创建对象?

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

In JavaScript, I can create an object like this: 在JavaScript中,我可以创建这样的对象:

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

I'm trying to do something like this ( JSFiddle ): 我正在尝试做这样的事情( 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" . 但是结果将是"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. 我不想使用JSON格式,因为JSON要求在每个属性名称中都使用双引号,因此经常键入非常麻烦,查看起来并不方便,并且会导致字符串更大。 If possible, I wish to work with JavaScript object literal notation. 如果可能,我希望使用JavaScript对象文字表示法。

EDIT 2: this is what I'll be working on (with more time). 编辑2:这就是我将要从事的工作(需要更多时间)。 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);

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

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