The array containing JSON objects enclosed within curly braces is causing a syntax error

Given a variable containing data that looks like an "array" with JSON Objects inside (even though it is not actually formatted as an array, starting and ending with curly braces):

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

How can I transform this so that the initial and final { curly braces } are replaced with square brackets [ ]? JavaScript does not recognize this format as an array, resulting in an error. Utilizing JSON.stringify or JSON.parse also proves ineffective since the structure is not genuine JSON/Array. Only when it is enclosed in [ square brackets ] will it be perceived as an array with JSON objects within:

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

I considered converting it into a string initially, and then substituting the first and last characters with [ and ] correspondingly. However, attempting String(value) on the original "array" results in errors, being interpreted as JSON leading to unexpected tokens if initialized.

Answer №1

If you want to create an array of JSON objects, you can follow this approach:

const data = new Array(
  { 'a1': 'a2' },
  { 'b1': 'b2' },
  { 'c1': 'c2' }
);

console.log( data[0] );

You should see the following result in the console:

{
a1: "a2"
}

I hope this information is useful to you.

Answer №2

Comments have highlighted the fact that your input JSON format deviates from standard JSON requirements, necessitating a custom parsing solution. Below is an excerpt hastily adapted 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();
}

Answer №3

If you receive this information from someone, it is important to kindly let them know that the data provided is not valid.

I prefer not having to work with faulty data. Let's address the issue at its source rather than finding ways to work around it repeatedly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on how to showcase it to cover a wide area

I'm having trouble figuring out how to display the output in a span element. Every time I try, I just get a blank result, and when I alert the txtNumber variable, I see "object html span element" in the alert message. <span id="displayQty"> num ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...

Mapping various sets of latitudes and longitudes on Google Maps

I am working with multiple latitude and longitude coordinates. var latlngs = [ {lat:25.774252,lng:-80.190262}, {lat:18.466465,lng:-66.118292}, {lat:32.321384,lng:-64.757370}, {lat:25.774252,lng:-80.190262}, ]; The coordinates were ret ...

Order Varchar Data Array in Ascending Order using PHP

Is there a way to use PHP code to sort an array of varchar data in ascending order? I attempted it myself and the current result is : ABC1 ABC10 ABC11 ABC11A ABC11B ABC2 ABC2A ABC20 ABC3 However, my desired output is : ABC1 ABC2 ABC2A ABC3 ABC10 ABC11 A ...

Troubleshooting TypeScript Modules in Visual Studio 2015 Update 2: Fixing the 'require' Undefined Error

While working in Visual Studio 2015 Enterprise with Update 2 installed, I decided to create a new TypeScript project called TypeScriptHTMLApp1 using the default template and settings. As part of this project, I added a new TypeScript file named log.ts and ...

Can $.ajax be used as a replacement for $(document).ready(function()?

After conducting an extensive search, I am still unable to find a clear answer to my assumption. The code I used is as follows: <?php session_start(); if (isset($_SESSION['valid_user']) && $_SESSION['from']==1) { ?> ...

json_normalize is experiencing difficulty in flattening a column that contains a List of Dictionary

I've been struggling to flatten the column sellers.price_data for a while now, with no success. This specific column is the final one in the table output displayed below. To reach this point, I had to normalize and expand the data obtained from the AP ...

Response text from AJAX in PHP

I am working on an AJAX sign up form and I would like to incorporate a gear wheel animation similar to this When the server successfully signs up a user, I want a specific bar to change to green. To achieve this, I have echoed the names of the functions I ...

Utilizing JSON for HTML conversion in Codeigniter

public function getCrew(){ $search = $this->input->post('name'); if($this->input->post('ajax') && (!empty($search))){ $result = $this->model->getNames($search); foreach($result as $r){ ...

What is the best way to select a specific button to handle the onSubmit event in a React form with multiple buttons

Imagine having the following HTML structure: <div id="container"></div> <p>Output: <span id="output"></span></p> accompanied by this block of JS code: function otherAction(e) { document.getElementById('output& ...

Tips for dynamically updating an HTML value with Javascript

Summary of My Issue: This involves PHP, JS, Smarty, and HTML <form name="todaydeal" method="post"> <span id="fix_addonval"></span> <input type="radio" name="offer" id="offer_{$smarty.section.mem.index+1}" value="{$display_offe ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...

Changing the Class of an Element in a Different Component with Angular 2+

Currently in a project utilizing Angular 4, I have implemented two components: app.component and other.component Within app.component.html, there exists a div with the name attribute myClass. <div class="myClass"></div> In the other.componen ...

Ways to retrieve information from a request handler

Working with express, node, and handlebars, I've implemented this piece of code to manage POST requests. When a user hits the "add item" button, it captures their input for a city, fetches the weather data for that city using the Open Weather Map API, ...

Converting a timestamp from PHP in JSON format to date and time using JavaScript

Within the JSON file, there is a timestamp associated with each user login. An example of this timestamp is: timestamp: "1541404800" What steps should be taken to convert this timestamp into date and time format? ...

The retrieval of JSON file using $.GetJson() is unsuccessful from local directory

There is a basic autocomplete program in place. The data entered in the textbox is successfully captured while debugging, however, the GetJson() function fails to retrieve the JSON file, causing the program to malfunction. Here's the relevant code sn ...

Using jQuery to fetch and read the source code of a specified URL

I'm facing an issue with extracting the source code of a website URL into a variable. Here is my current approach: <script type="text/javascript"> debugger; $(documnet).ready(function () { var timer = $.ajax({ type: ...

Having trouble with accessing an element that contains both onclick and text attributes in Selenium Webdriver?

The HTML code I'm dealing with includes this element: <a style="text-decoration:none; font-weight:normal;" href="javascript:void(0);" onclick="CreateNewServiceItemApproved();"> <img src="icons/ui/addnew.png"> <span style="color:# ...

Directly transfer image to Cloudinary without creating a local file

I have integrated jdenticon to create user avatars upon signup in a node/express app. When working locally, I follow these steps: Create identicon using jdenticon Save the file on my local machine Upload the local file to cloudinary Here is a snippet o ...

Incorporate ng-click as an attribute in AngularJS

Is there a way to include ng-click as an attribute? For example, imagine I want to add ng-click if my <li> has the class someClass: angular.element(root.querySelector('li.someClass').attr({'ng-click': 'someFunc()'}); ...