简体   繁体   中英

Array with JSON Objects inside that are written starting and ending with curly braces error

I am given an "array" with JSON Objects inside like so (it's not an actual array since it begins with curly braces):

     {{"x1","x2"},{"y1","y2"},{"z1","z2"}}

How can I make it so that the first and last { curly braces } becomes square braces [ ]? Javascript does not recognize the above example as an array and throws an error. Calling JSON.stringify or JSON.parse does not work either since the above is not actual JSON/Array. Only when it has [ square brackets ] does it actually work since then it is an array with JSON objects inside it. Like so:

    [{"x1","x2"},{"y1","y2"},{"z1","z2"}]

I was thinking of making it into a string first, then replacing the first and last char with [ and ] respectively, but calling String(value), where value is the first "array", simply doesn't cut it as it thinks it is a JSON and throws unexpected token if I even declare it.

If you're trying to create an array of JSON objects, you could do as follow:

const object = new Array(
  { 'x1': 'x2' },
  { 'y1': 'y2' },
  { 'z1': 'z2' }
);

console.log( object[0] );

expecting in the console the following result:

{
x1: "x2"
}

Hope it helps.

As it was already pointed out in comments, your input JSON isn't really JSON at all - you'll want a custom parser for it. Here's something quickly scrambled from Haxe's haxe.format.JsonParser:

var Std = function() { };
Std.parseInt = function(x) {
    if(x != null) {
        var _g = 0;
        var _g1 = x.length;
        while(_g < _g1) {
            var i = _g++;
            var c = x.charCodeAt(i);
            if(c <= 8 || c >= 14 && c != 32 && c != 45) {
                var nc = x.charCodeAt(i + 1);
                var v = parseInt(x,nc == 120 || nc == 88 ? 16 : 10);
                if(isNaN(v)) {
                    return null;
                } else {
                    return v;
                }
            }
        }
    }
    return null;
};
var StringBuf = function() {
    this.b = "";
};
var JsonParser = function(str) {
    this.str = str;
    this.pos = 0;
};
JsonParser.prototype = {
    doParse: function() {
        var result = this.parseRec();
        var c;
        while(true) {
            c = this.str.charCodeAt(this.pos++);
            if(!(c == c)) {
                break;
            }
            switch(c) {
            case 9:case 10:case 13:case 32:
                break;
            default:
                this.invalidChar();
            }
        }
        return result;
    }
    ,parseRec: function() {
        while(true) switch(this.str.charCodeAt(this.pos++)) {
        case 9:case 10:case 13:case 32:
            break;
        case 34:
            return this.parseString();
        case 123:
            var arr = [];
            var comma = null;
            while(true) switch(this.str.charCodeAt(this.pos++)) {
            case 9:case 10:case 13:case 32:
                break;
            case 44:
                if(comma) {
                    comma = false;
                } else {
                    this.invalidChar();
                }
                break;
            case 125:
                if(comma == false) {
                    this.invalidChar();
                }
                return arr;
            default:
                if(comma) {
                    this.invalidChar();
                }
                this.pos--;
                arr.push(this.parseRec());
                comma = true;
            }
            break;
        default:
            this.invalidChar();
        }
    }
    ,parseString: function() {
        var start = this.pos;
        var buf = null;
        var prev = -1;
        while(true) {
            var c = this.str.charCodeAt(this.pos++);
            if(c == 34) {
                break;
            }
            if(c == 92) {
                if(buf == null) {
                    buf = new StringBuf();
                }
                var s = this.str;
                var len = this.pos - start - 1;
                buf.b += len == null ? s.substr(start) : s.substr(start,len);
                c = this.str.charCodeAt(this.pos++);
                if(c != 117 && prev != -1) {
                    buf.b += String.fromCodePoint(65533);
                    prev = -1;
                }
                switch(c) {
                case 34:case 47:case 92:
                    buf.b += String.fromCodePoint(c);
                    break;
                case 98:
                    buf.b += String.fromCodePoint(8);
                    break;
                case 102:
                    buf.b += String.fromCodePoint(12);
                    break;
                case 110:
                    buf.b += String.fromCodePoint(10);
                    break;
                case 114:
                    buf.b += String.fromCodePoint(13);
                    break;
                case 116:
                    buf.b += String.fromCodePoint(9);
                    break;
                case 117:
                    var uc = Std.parseInt("0x" + this.str.substr(this.pos,4));
                    this.pos += 4;
                    if(prev != -1) {
                        if(uc < 56320 || uc > 57343) {
                            buf.b += String.fromCodePoint(65533);
                            prev = -1;
                        } else {
                            buf.b += String.fromCodePoint(((prev - 55296 << 10) + (uc - 56320) + 65536));
                            prev = -1;
                        }
                    } else if(uc >= 55296 && uc <= 56319) {
                        prev = uc;
                    } else {
                        buf.b += String.fromCodePoint(uc);
                    }
                    break;
                default:
                    throw new ("Invalid escape sequence \\" + String.fromCodePoint(c) + " at position " + (this.pos - 1));
                }
                start = this.pos;
            } else if(c != c) {
                throw new ("Unclosed string");
            }
        }
        if(prev != -1) {
            buf.b += String.fromCodePoint(65533);
            prev = -1;
        }
        if(buf == null) {
            return this.str.substr(start,this.pos - start - 1);
        } else {
            var s1 = this.str;
            var len1 = this.pos - start - 1;
            buf.b += len1 == null ? s1.substr(start) : s1.substr(start,len1);
            return buf.b;
        }
    }
    ,invalidChar: function() {
        this.pos--;
        throw "Invalid char " + this.str.charCodeAt(this.pos) + " at position " + this.pos;
    }
};
JsonParser.parse = function(s) {
    return new JsonParser(s).doParse();
}

If someone is giving you this you really ought to go back to the source and inform them that they are NOT providing you with a valid input.

I avoid having to hack around poor source data. Fix it at the source and not have to deal with it everywhere that it is used.

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