Best way to convert string to array of object in javascript?

后端 未结 6 1280
萌比男神i
萌比男神i 2020-11-27 19:21

I want to convert below string to an array in javascript.

{a:12, b:c, foo:bar}

How do I convert this string into array of objects? Any cool

6条回答
  •  庸人自扰
    2020-11-27 19:27

    Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error. It's also not an Array but a HashMap or simply an Object literal (malformed). If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.

    function malformedJSON2Array (tar) {
        var arr = [];
        tar = tar.replace(/^\{|\}$/g,'').split(',');
        for(var i=0,cur,pair;cur=tar[i];i++){
            arr[i] = {};
            pair = cur.split(':');
            arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
        }
        return arr;
    }
    
    malformedJSON2Array("{a:12, b:c, foo:bar}");
    // result -> [{a:12},{b:'c'},{foo:'bar'}]
    

    That code will turn your string into an Array of Objects (plural).

    If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:

    function malformedJSON2Object(tar) {
        var obj = {};
        tar = tar.replace(/^\{|\}$/g,'').split(',');
        for(var i=0,cur,pair;cur=tar[i];i++){
            pair = cur.split(':');
            obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
        }
        return obj;
    }
    
    malformedJSON2Object("{a:12, b:c, foo:bar}");
    // result -> {a:12,b:'c',foo:'bar'}
    

    The above code will become a lot more complex when you start nesting objects and arrays. Basically you'd have to rewrite JSON.js and JSON2.js to support malformed JSON.

    Also consider the following option, which is still bad I admit, but marginally better then sticking JSON inside an HTML tag's attribute.

    bla

    I am assuming you omit quote marks in the string because you had put it inside an HTML tag's attribute and didn't want to escape quotes.

提交回复
热议问题