Guide to transforming a Javascript array into a JSON string

There is an array named values that contains the following data:

var values = new Array();
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav");

When using JSON.stringify(values), the output includes square brackets, but a JSON string in the format below is needed with urllist added at the beginning.

{
   "urlList": {
      "english": "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav",
      "kannada": "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"
   }
}

Answer №1

The code you have written will produce errors, as it is not valid JavaScript. You cannot create an array element in that way.

values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");

If you intend to have the structure specified in your question, you should use a nested object instead of an array to store key/value pairs.

var values = {
  urlList: {}
};

values.urllist.english = "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav";
values.urllist.kannada = "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav";

DEMO

HOWEVER...

If you meant to write this code (notice the curly braces):

var values=new Array();
values.push({"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"});
values.push({"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"});

This indicates that you are pushing objects into an array, which is perfectly valid JavaScript.

To convert the array data into the desired structure, you can use a loop like this:

var out = {
    urlList: {}
};

for (var i = 0, l = values.length; i < l; i++) {
  var el = values[i];
  var key = Object.keys(el);
  var value = el[key];
  out.urlList[key] = value;
}

JSON.stringify(out);

DEMO

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

Updating multiple collections in MongoDBRestructuring data across multiple

Imagine a scenario where an API call must update two different collections. It's crucial that if one update fails, the first update needs to be reverted. How can I guarantee that both operations either complete successfully or none at all? Let me prov ...

What exactly does the .proxy() method do in jQuery?

Can you explain the purpose of the jQuery.proxy function in jQuery and describe the scenarios where it is most beneficial? I came across this link, but I'm struggling to grasp its concept fully. ...

Unable to get dataLayer.push to function following installation of GTM script

I am looking to incorporate Enhanced Ecommerce using Google Tag Manager and I need to send additional data for the Universal Analytics tag. Usually, I have created the dataLayer before the GTM script, but now I need to push more data with dataLayer.push ...

How to dynamically populate a Vue multiple select dropdown with v-for loop?

I have been attempting to implement multi-select questions in Vue using v-for. The Select menu and its options are populated via JSON data. Unfortunately, I am facing difficulty in retrieving the selected results as expected. Whenever I select an option ...

JavaScript Accordion malfunctioning

I'm attempting to implement an accordion feature for each row of an HTML table using the script provided below HTML <table class="list" id="table" data-bind="visible: !loading()"> @*<table class="productTable" data-bind="sortTable:true" ...

Ways to substitute characters within a string value

Here is a JavaScript code snippet that I am working with: var a=camera.getDetails();// (say a=["1","2"] as arraylist/array) var c=new Array(a); alert(c); window.location="my_details.html?"+c.join(",")+ "_"; Now, in my_details ...

I am interested in utilizing the fromJson() method of GSON to transform my JSON object into my Java object

I am faced with a JSON object structured like this: [ { "created_at": "2014-07-01 5:01:10", "status": "in progress", "device_id": "1234", "order_details": [ { "item_id": 1, "q ...

Tips on refreshing HTML content by locating a specific attribute

<li class="person" data-chat="person1"> <img src="http://s13.postimg.org/ih41k9tqr/img1.jpg" alt="" /> <span class="name">user name</span> <span class="time">0:00 AM</span> <span class="preview">las ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

Displaying a JSON array in C++ using the nlohmann library

I utilized the nlohmann library to create JSON objects with the following code snippet: nlohmann::json dataJson; auto data = dataJson.array(); data[0]["message"] = "String"; data[0]["timestamp"] = 123; The current output is {"message":"String", "timest ...

Adjusting the input in a Textfield within React using Material UI

const [formData, setFormData] = useState({}); useEffect(() => { fetch("/formdata") .then((res) => res.json()) .then((data) => setFormData(data)); }, []); console.log("Form Data", formData); //Sorting by order let attr; ...

What is the best way to represent objects in a user interface?

Currently, I have some information stored in the following format: data : { full_name: 'John Doe', date_of_birth: '01-01-1990' } I am looking to display this data in a table-like format that resembles: Full Name: John Doe Date Of B ...

Webpack is throwing an error stating that it cannot find a module with the relative path specified

Here is the structure of my app (excluding the node_modules directory): ├── actions.js ├── bundle.js ├── components │   ├── App.js │   ├── Footer.js │   ├── Link.js │   ├── Todo.js │   └─ ...

What is the process for uploading an image and entering text into the same row in Google Sheets?

Hello, I am currently working on a Google Script web app that enables users to upload 10 photos along with comments for each photo. This information will then be inserted into a Google Sheet when the user clicks the 'upload' button on the web app ...

Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to updat ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

The timing calculations in Vue.js do not align with the standard JavaScript version

I am currently working on developing a 'beats per minute' (BPM) calculator, which is similar to the one available here. However, I have noticed that when using the BPM calculator from that link for testing on a particular song, it quickly approxi ...

Pattern Matching: Identifying partial or complete text

Currently, I'm facing challenges with a small script that is designed to compare the value from a text input with items in an array either partially or completely. I am struggling specifically with the regular expression and its syntax. I was hoping ...

Creating a dynamic method to set data for a stacked bar chart in chart.js

In the following code snippet, you can see how my stacked bar chart is rendered using Angular: <canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]=" ...

Using the v-for directive in Vue.js to loop through an array and display

Looking at the image provided, I am trying to access the content. I attempted to do so using element.comments.content, but it did not seem to work as expected. Here is the snippet of code: <div class="fil-actualites-container"> <div cl ...