How can I interpret a string with a specific format using JavaScript?

Input String:

var json_data = "{0:'apple', 1:'bannana', 2:'guava'}";

Desired Output after parsing with JavaScript:

var json_data = {
  columns: [{0:'apple'}, {1:'bannana'} ,{2:'guava'}]}

I attempted to convert it using the following code, but I was unsuccessful...

json_data = JSON.parse('{"columns": [{"":""}]}')

Answer №1

Attempt to parse the provided string:

JSON.parse(parsed_json.replace(/(\d+)\:/g,'"$1":').replace(/'/g,'"'))

Answer №2

When referring to the JSON schema documentation, it becomes evident that your original string does not align with the JSON definition:

The initial string provided:

{0:'apple', 1:'bannana', 2:'guava'}

This is inaccurate for a few reasons:

  1. Object keys should be strings (Numbers like 0 or 1 cannot be used, but strings like "0" or "1" are acceptable)

  2. Strings need to be enclosed in double quotes "

A possible correction for the JSON representation of your data:

{"0":"apple", "1":"bannana", "2":"guava"}

// Consider enclosing this in different quotation marks for JavaScript
var json_d = `{"0":"apple", "1":"bannana", "2":"guava"}`;
// Alternatively, escape the double quotes
var json_d = "{\"0\":\"apple\", \"1\":\"bannana\", \"2\":\"guava\"}";

Or:

["apple", "bannana", "guava"]

// Wrap this in a different set of quotes for JavaScript
var json_d = `["apple", "bannana", "guava"]`;
// Or use escaped double quotes
var json_d = "[\"apple\", \"bannana\", \"guava\"]";

Tip: Utilize reputable JSON validators online, such as:

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

How can Ext JS 4 handle the transmission of multiple metaData to support multiple dynamic grids by utilizing a single JSON file?

Looking to create multiple grids on a single panel using an accordion layout? I'll be dynamically generating all the grids based on metaData in JSON and handling metachange listener events on my store to reconfigure the grid. But here's the quest ...

Error encountered: JSON Exception - Unable to locate the key "Name" in the JSONObject

I am looking to retrieve the value "Automation Admin" from the JSON output below, but I keep encountering a JSONObject["Name"] not found exception. Here is the code snippet: I attempted to replace ownerName = json.getJSONArray("records").getJSONObject(i) ...

The innerHTML feature in Javascript seems to be malfunctioning

Having a simple javascript issue here. I am attempting to retrieve a date from a textbox and display it in a label for another purpose. However, I encountered some problems along the way. I can successfully alert the date retrieved from the textbox, but wh ...

Create a smooth scrolling effect for a div with a fixed position

Having trouble scrolling a fixed position div on the page? Are you using this jquery script: $('html, body').animate({ scrollTop: $(".example").offset().top }, 750); I had to set the body overflow property to hidden for another issue. The ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...

Verify the presence and delete a table row from the JSON data that is returned

Is there a way to verify the presence of a label in the JSON response and exclude it from the displayed row in my table? In the code snippet below, you can observe that I am returning 'Page Name not defined'. I want to hide this label and any re ...

Update the URL using JQuery and Ajax without having to reload the page, ensuring compatibility with Internet Explorer versions 8 and 9

Upon the initial loading of my webpage, it directs to the following URL: /default/ After clicking the "nextPost" button on the screen (which includes an attribute named data-nextPostNumber), the corresponding code is as follows: event.preventDefault(); ...

How can I transform an HTML element into a textarea using CSS or JavaScript?

While browsing a webpage, I discovered a <div> element with the class .plainMail and I want to find a way to easily select all its text by simply pressing Ctrl+A. Currently using Firefox 22, I am considering converting the div.plainMail into a texta ...

Can an in-progress NPM package be tested using NPX?

I am currently developing an NPM package that is designed to be used exclusively through npx *, similar to packages like create-nuxt-app. Is there a method to test my package using npx *? Essentially, I want to run my bin script without actually installin ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Preventing Page Scroll While New Data is Loading

I am currently working on a React class component that uses Post components. Within this component, there is a button that triggers the loading of more data from the database. The issue I am encountering is that when new data is fetched, the page automatic ...

Tips for creating an endless scrolling/loader feature in Nuxt?

Hey there! I am looking to display data after implementing infinite loading. The data is sent asynchronously using asyncData to the page with an ID. Page <script> export default { async asyncData({ $axios, store }) { const customerId = store.g ...

Exploring Angular unit testing using Jasmine: Techniques to customize or delete spyOn

Current software versions for AngularJS and Jasmine: AngularJS v1.2.26 Jasmine v2.2.0 I am facing an issue with a spyOn. When attempting to change or remove its behavior, I encounter the following error message: Error: getUpdate has already been spied u ...

The function is attempting to access the 'lockDatabase' property of an undefined object, resulting in an error

I'm encountering an error due to the scope issue with 'this', and I'm struggling to find a solution. I attempted using the fat arrow, which solved the scope problem but created another issue where I lack a callback value that needs to b ...

WCF JSON Post functions correctly in Visual Studio but encounters issues in IIS 7.5

I'm experiencing a strange issue with my WCF Service in IIS. GET requests are functioning properly, but when it comes to POST requests, they only work when I run the service from Visual Studio. When I try to use IIS, I receive an Error 400 Bad Request ...

On the hunt for a specialized JavaScript library for input validation?

Have you ever come across a JavaScript library that allows for variable validation in a convenient chaining style like this one? For example: if(insertLibraryNameHere(myNumberInput).int().min(0).max(10)) This library also has checks for other data types ...

What is the best way to transfer information from a view to a controller in Laravel using AJAX?

I am facing an issue with sending data from the view to the controller in Laravel version 7 I am sending data from a form and ul li elements I have an array of data in JavaScript Here is my HTML code: <ul name="ali" id="singleFieldTags&q ...

Page can be accessed using file_get_contents function but not with cURL

In the process of creating an API endpoint in PHP, a scenario arose where JSON data output from a specific page example.com/stats was causing issues with cURL requests compared to using file_get_contents(). How can I ensure that JSON data served in PHP is ...

Vue: the parent template does not permit the use of v-for directives

Upon creating a simple post list component, I encountered an error when trying to utilize the v-for directive: "eslint-eslint: the template root disallows v-for directives" How can I go about iterating through and displaying each post? To pass data from ...

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...