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

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

Traversing a JSON array using Shell scripting techniques

Within my data.json file, I have JSON data structured like this: [ {"original_name":"pdf_convert","changed_name":"pdf_convert_1"}, {"original_name":"video_encode","changed_name":"video_encode_1"}, {"original_name":"video_transcode","changed_name":"v ...

What is the best way to set the first radio button as the default selection in Material UI?

The challenge I am facing involves a set of radio buttons representing dates from today to 30 days in the future. When a radio button is selected or active, it changes the background color. However, I would like the default selection to be the first radio ...

Google Docs integrated with JqueryMobile for seamless document creation and editing

Recently, I experimented with a plugin that allows for viewing pdf documents directly in the browser. While it worked flawlessly on my desktop browser, I encountered some display issues when trying to access it from my mobile device. The document didn&apos ...

Converting a table into JSON format

I'm working on developing a live application that will showcase data in a table format like the one below: Machine Production Scanned Delta Mach 1 2500 1000 1500 Mach 2 1500 1300 200 Mach 3 6500 5000 1500 Mac ...

Updating a specific field within an embedded Mongo document without altering any other fields

I'm experiencing an issue with my code that involves basic updates on a Mongo document. The issue arises after executing the /stop/:id route, where the startDate field in the embedded document is being inadvertently deleted. What steps can I take to e ...

Utilize the Google reverse geocoding API to convert latitude and longitude values from JSON into a dynamic variable

I have been utilizing the NPM Geocoder to convert locations into latitude and longitude coordinates, but I am struggling with extracting the lat and long values from the output. Below is the JSON data, and my goal is to store the values on lines 59 and 60 ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

Troubleshooting issue with AngularJS ng-repeat not functioning properly when using Object key value filter with ng-model

Is there a way to have an object with an ID as a key value pair? For example: friends = { 1:{name:'John', age:25, gender:'boy'}, 2:{name:'Jessie', age:30, gender:'girl'}, 3:{name:'Johanna', ag ...

Uninitialized Array Member in Angular 8

Can anyone explain why the code snippet below is printing "undefined"? I have created several objects and intended to display the corresponding images, but after iterating through them using ngfor, nothing appeared. To investigate, I logged the array and ...

Sending JSON data to a specific URL using cURL

I am searching on stackoverflow for a solution, but any help is appreciated. I need to send the following json-rpc code to another file which contains a bottle server: curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method":" ...

implementing datepicker on multiple textboxes in jQuery upon button click

I have the ability to show multiple text boxes using jQuery. I am now looking to add a datepicker to those text boxes. Any assistance in finding a solution would be greatly appreciated. Thank you in advance. ...

Unable to add key/value pair to object in Node

While using Node, I encountered a strange issue where I was unable to attach the key/value pair broadcastStamp = date to the object "result." Despite confirming that it is indeed an object with typeof, no errors were thrown - the key/value simply did not a ...

What steps can I take to convert my React class into a function in order to incorporate Material UI components effectively?

With Emailjs set up successfully, my next step is integrating Material UI text fields (link: https://material-ui.com/components/text-fields/#text-field) to enhance the design of my project. The challenge I'm facing is incorporating Material UI classe ...

Submitting a form and obtaining results without relying on jQuery

Finding information on how to accomplish this task without using jQuery has proven to be a challenge. It seems like everyone is pushing for jQuery for even the simplest tasks nowadays. Despite avoiding unnecessary use of jQuery in creating a rich experienc ...

The EJS template in an Express.js (Node.js) application is not updating to show recent modifications

I'm currently developing a node.js application that serves an index.ejs page through a route named index.js. var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) ...

display a dual-column list using ngFor in Angular

I encountered a situation where I needed to display data from an object response in 2 columns. The catch is that the number of items in the data can vary, with odd and even numbers. To illustrate, let's assume I have 5 data items to display using 2 co ...

Caution: Discrepancy found in Prop className between server and client rendering in a React SSR application

Currently, I am working on integrating a collapsible sidebar into my React application that relies on a value stored in the local storage. The intended behavior is for the sidebar to have the className of "inline" if the value is true, and "hidden" if the ...

What steps can be taken to create a progress bar in the input field that spans the entire width of its parent div, reaching

I received assistance from a friend in creating this progress bar. Everything seems to be working well, except for the fact that the progress bar is not extending to the full width of the parent div. The new width after each input tag is entered using Java ...

The Angular datepicker is failing to trigger the ng-change event

I've run into a snag with the datepicker and ng-change functionality. Oddly enough, the ng-change event isn't triggering when I manually select a date by clicking on it, but it works fine when I input a date manually. Take a look at my code snip ...