Transform an array containing strings into an array containing objects within a JSON property

I have received the following JSON data from an endpoint:

{
    "response": {
        "lines": [
            "[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':'international'}]",
            "[{'line':'3007262p7f6','type':'national'},{'line':'3007262a0s1','type':'international'}]"
        ]
    }
}

The property lines is intended to contain multiple arrays, but in this case it is an array of strings. How can I convert each individual string in the lines property into an array of objects?

Thank you

Answer №1

If you're looking for a simple way to transform strings into arrays, one effective method is to use the eval() function.

var data = {
  "content": {
    "blocks": [
      "[{'block':'8473jsk8s2','type':'section'},{'block':'9372kdf9s9','type':'subsection'}]",
      "[{'block':'7362jdl6p5','type':'section'},{'block':'9372ksl1a0','type':'subsection'}]"
    ]
  }
}

data.content.blocks = data.content.blocks.map(block => eval(block));

console.log(data);

Answer №2

There seems to be a couple of mistakes in your JSON data (I am not sure if this is the actual JSON or if it was hardcoded, so you might want to double-check). The first issue is

  • 'line:'3007621h7s2 should be 'line':3007621h7s2
  • Values such as 3007621h7s2 should be '3007621h7s2'

Once you correct your JSON, you can utilize JSON.parse() to parse the string successfully

var data = {
    "response": {
        "lines": [
            "[{'line':'3007621h7s2', 'type': 'national'},{'line':'3007663f7s9','type':'international'}]",
            "[{'line':'3007262p7f6', 'type': 'national'},{'line':'3007262a0s1','type':'international'}]"
        ]
    }
}

data.response.lines = data.response.lines.map(a=>JSON.parse(a.replace(/'/g,'"')))

console.log(
  data
)

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

eliminate whitespace characters within a string

Here is a question that suggests an easy way to remove space characters in a string using R. However, I encountered an issue when trying to remove a space between two numbers (e.g. 11 846.4) while working with the following table: require(XML) require(RCur ...

Bug allows unauthorized access to password in Bootstrap Password Revealer

Whenever I try to reveal a Bootstrap password using the eye button, my PC freezes. Strangely, an input is automatically added even though there are no codes for it. This auto-increasing input causes my browser to hang and eventually crashes my entire PC. C ...

Switch up the text when the image link is being hovered over

Is there a way to change the text color of the "a" tag when it is not wrapping the img link? <li> <a href="# WHEN I HOVER THIS IMG LINK I WANT A TAG BELOW TO CHANGE COLOR"> <img alt="Franchise 16" src="#"></img> < ...

Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu. The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/form ...

Issue with the intersection of mouse and camera rays in three.js

I've been working on a simple program that involves creating a clickable 3D object in Three.js. I've referenced my code from When I click directly on the object, it works as expected, but upon examining the resulting array, I noticed that the ob ...

Tips for confirming schedule accuracy

Trying to determine if a specific time falls between two others is the task at hand. Allow me to illustrate: Presently, it's Thursday, and the time reads 11:39 PM. Establishment X operates from 12:00 AM to 11:59 PM on Thursdays (a regular occurrence ...

Populating an array prior to AJAX transmission

I'm not a JavaScript expert, particularly when it comes to promises and callbacks. However, my goal is to have my JavaScript file perform the following tasks synchronously: 1. Create an array 2. Populate the array with all the necessary elements 3. Se ...

Vue.js methods bound as properties on a parent object

There are times when I come across scenarios where it would be convenient to bind methods as an object property rather than a direct Vue method. For instance, instead of: <MyInput :formatter="currencyFormat" :parser="currencyParser& ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Leveraging getScript to extract JSON data from a different domain

I've successfully implemented a local script that retrieves data from a JSON file: $.getJSON("jsonfile.js",function(item) { $.each(item.terra_nova_feed, function(i,item) { // functions and variables// }); }); However, when the JSON file ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Ways to fill in nested fields within a MongoDB schema

My schema consists of a summary structure: { sender: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true, }, summary: { type: String, }, sent: { type: Date, default: Date.n ...

Having trouble submitting a form in React JS

I'm facing an issue with my form where I am trying to print the data in console upon submission, but for some reason it's not working. The form is not submitting and I can't figure out why. Below is the code I have written. Any help would be ...

Discover additional Atom extensions

I am exploring the possibility of implementing a feature in my Atom package where it can automatically detect whether specific third-party packages have been installed. Currently, my package adds configuration for one such third-party package, but I want t ...

AngularJS directive error: Incorrect function invoked

I have two similar scenarios where I need to apply validators for specific files, even though I am aware that this goes against the DRY principle. However, being new to AngularJS, I am still learning the ropes. module.js var $moduleExample = angular.modu ...

Navigate to the appropriate Angular route using HTML5 mode in Rails

After removing the '#' symbol in angular by using html5Mode, everything seemed to work fine. However, upon refreshing the page, it started looking for the template in Rails instead of Angular, resulting in a "template not found" error. Angular R ...

Using Python to extract data from JSON containing multiple objects

I have a JSON file that contains multiple objects and I am attempting to parse it based on one of the values in each object. However, I am unsure if my current method is capable of achieving this. JSON [{"Temp":512,"Name":"sdfd3","SearchTags":["North"]}, ...

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

Utilizing asynchronous false in Wordpress Ajax functionality

Is there a way to use the AJAX return value outside the function in WordPress? For example: function get_login_member($) { $.post(ajax_object.ajax_url, {action: 'getloginmember'}, function (data) { data = JSON.parse(data); ...

Steps to resolve the days.map error:

My map function is, days.map((val)=>val) Upon consoling the days prop, I receive the following output: [Array(7)] 0: (7) ['', '', '', 'Wednesday', '', '', 'Saturday'] length: ...