Transform a string-formatted array into a JavaScript array

Currently, I'm dealing with an array that is stored in string format,

var str = { 
    id: 123,
    changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}
var d = str.changes

I've attempted different methods to convert the 'changes' array from its string format, including using split(), replace(), slice(), and even JSON.parse(), but all my efforts have been unsuccessful so far.

Do you know of any effective way to transform this into a javascript array?

Answer №1

Remember that the input provided is not a valid JSON string, nor is it a valid array.

If possible, try to convince the server to send a valid JSON string instead.

"[{\"atr\":\"test1\", \"old\":null, \"new\":null}, {\"atr\":\"messageText\", \"old\":\"test here\", \"new\":\"hello test\"}, {\"atr\":\"status\", \"old\":null, \"new\":1}]"

If the response always follows the same format as shown, then you can convert it into valid JSON like below:

var str = {
  id: 123,
  changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}

// Replace inner [ ] with { }
let changes = str.changes.replace(/\[\[/g, "[{").replace(/\], \[/g, "},{").replace(/\]\]/g, "}]")

// Convert unquoted keys and values to quoted
changes = changes.replace(/(\w+):/g, '"$1":').replace(/:([\w ]+)([},])/g, ':"$1"$2')

// Parse the object
changes = JSON.parse(changes);

// Replace "null" with null
changes.forEach(item => Object.keys(item).forEach(key => item[key] = item[key] === "null" ? null : item[key]))

console.log(changes)

Answer №2

It seems that the issue lies with the content of the key 'changes' not being in valid JSON format. You can check and correct it by using this online tool.

If the content within the 'changes' key is valid JSON, you can easily convert it into a JavaScript array using JSON.parse(), like so:

var data = { 
    id: 123,
    changes: `[{"atr": "test1", "old": null, "new": null},
              {"atr": "messageText", "old": "test here", "new": "hello test"},
              {"atr": "status", "old": null, "new": 1}]`
};

var parsedData = JSON.parse(data.changes);
console.log(parsedData);

// Output of parsedData:
[{atr: "test1", new: null, old: null}, 
 {atr: "messageText", new: "hello test", old: "test here"}, 
 {atr: "status", new: 1, old: null}]

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

Utilize Vue 2.0 to retrieve input from the getmdl-select component

Experimented with getmdl-select using Vue2.0. Managed to get it to display correctly in the view, but the associated model is not updating. Here is the code snippet: <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select ...

When transferring files to the src/pages directory in Next.js, the custom _app and _document components are not recognized

The documentation for Next.js mentions that the src/pages directory can be used as an alternative to /pages. However, I encountered a problem when moving my custom _app.tsx and _document.tsx files into the src folder, as they were being ignored. If you cr ...

Angular routing exhibits peculiar behavior with varying browsers

Recently, I completed a web project using AngularJS and Bootstrap with Brackets as my editing tool. Testing was done in Chrome through Brackets acting as the server. Everything worked perfectly on Windows 10 when tested locally or deployed on Tomcat as lon ...

Clickable Slider Picture

I'm having a minor issue with a jQuery script that slides images on my website. The script itself is functioning properly, but I am trying to add links to each image. I've attempted placing <a href> and </a> tags around the <img> ...

Is there a way to append the current path to a link that leads to another URL?

I am currently in the process of separating a website, with the English version being on the subdomain en. and the French version residing on the www. Before making this change, I have a drop-down menu that allows users to select their preferred language ...

Delaying the search in Jquery until the input is finalized

Is there a way to delay the search trigger until the user finishes typing? I'm utilizing a function created with mark.js () which initiates the search as the user types, resulting in jumping to the first result during the search. However, the issue is ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...

Why does MergeSort in C++ operate smoothly despite not returning anything?

I find the implementation of merge sort below quite perplexing. The code provided does not utilize pointers and does not return anything in `main()`. So, how does it manage to manipulate `myarray`? Can someone offer an explanation? Here is the code snippe ...

On Windows systems, where exactly does npm place its packages during installation when using Node version 10.x

Does anyone know where I can locate the locally installed npm modules when using NodeJS version 10? I have checked under C:\Users\MyUser\AppData\Roaming, but I cannot find the "npm" folder. ...

Error encountered in Three JS Drag Controls: Unable to assign value to property 'x' as it is undefined

I've been trying to drag the spheres around the scene using drag controls that should be activated when the "m" key is pressed. However, I keep running into an issue where the objects don't move and I receive an error message saying "Uncaught Typ ...

Prevent interruptions on mouse hover -Full Slider

In my most recent web development project, I incorporated the Full Slider component from Iron Summit Media (https://github.com/IronSummitMedia/startbootstrap-full-slider). It functions as a background image slider. However, I encountered an issue where ...

Guide to relocating a NumPy array into a different array

I have a situation where I need to store a numpy array returned by a function every second, in another array for reference. For example (array_a is returned) array_a = [[ 25. 50. 25. 25. 50. ] [ 1. 1. ...

The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/ Interestingly, the same script does not seem to work when embedded in an HTML document: <!DOCTYPE html> <html lang="en"> <head> & ...

The combination of select2 and jsonform is not functioning properly

I am having trouble rendering multiple select2 with JSON form. $('#resource-form').jsonForm({ schema: { rest: { type: 'object', properties: { template_id: { type: "array", items: { ...

Steps for creating an AJAX request to a variable defined within the local scope

I want to create a list using a JSON object that I already have stored in a variable. I have been exploring the dynatable library and its documentation on populating a table using AJAX to receive JSON data. However, I am stuck on how to make it work with ...

Error encountered while attempting to invoke endpoint function

Recently, I was handed a Node.js API documented with swagger for debugging purposes. My task also involves implementing some new features, however, I've encountered some difficulty when it comes to calling the functions that are executed upon hitting ...

Inject JSON result into an HTML div after an AJAX request

I have successfully implemented a JavaScript AJAX call that returns JSON data, and now I am trying to display it on my HTML page. Here is the code snippet I am using: success: function(response) { console.log(response); for (var i=0; i < response.len ...

How to retrieve the input value in React Autosuggest

I recently began my journey into learning JavaScript and React. Currently, I am working on creating a simple table with material design. The goal is to be able to add rows to the table through a form popup and delete rows using an icon within each row. On ...

Setting maxFontSizeMultiplier for all Text components

Is there a way to apply the prop maxFontSizeMultiplier={1} to all instances of <Text/> in my app without the need for a custom component? ...

Mysterious sayings encircling the words fetched through ajax

If the localhost is pointing to the folder named www, where the structure looks like: www/ file/test.cpp index.html I want to dynamically load the content of test.cpp into index.html and display it with the help of highlight.js. Below is the cod ...