The JSON string contains empty values

I'm attempting to convert my json data into a string -

for (var i = 0 ; i < lines.length ; i++) {

    var label = lines[i];
    var value = 1;

    item = [];
    item["label"] = label;
    item["value"] = value;

    jsonObj.push(item);
}

var jsonString = JSON.stringify(jsonObj);

While looping through, both label and value are assigned correctly with the appropriate values.

However, the jsonString appears to contain null values, causing confusion.

Answer №1

Remember to use item = {}; instead of item = [];.

The former is an object literal, while the latter is an array literal.

As an added precaution, use var items = {};

Answer №2

In this scenario, you start by initializing an array item = [] and then assigning string properties to it.

However, JSON.stringify assumes that an array should have numeric properties and therefore does not attempt to iterate over non-numeric properties.

A better solution would be to use an object instead {}

Here's an excerpt from the specification:

If Type(value) is Object, and IsCallable(value) is false
    If the [[Class]] internal property of value is "Array" then
        Return the result of calling the abstract operation JA with argument value.

followed by

Let len be the result of calling the [[Get]] internal method of value with argument "length".
Let index be 0.
Repeat while index < len
    Let strP be the result of calling the abstract operation Str with arguments ToString(index) and value.
    If strP is undefined
        Append "null" to partial.
    Else
        Append strP to partial.
    Increment index by 1.

References:

  • 15.12.3 stringify
  • 15.12.3 stringify JA

Answer №3

It's important to note that your item should be structured as an object. To help you get started, check out this JSFiddle with a simple example.

let item;
const lines = ["x","y","z"];
const jsonObject = {};
jsonObject.entries = [];

for (let i = 0 ; i < lines.length ; i++) {

    const label = lines[i];
    const value = 1;

    item = {};
    item["label"] = label;
    item["value"] = value;

    jsonObject.entries.push(item);
    console.log(jsonObject);
}

const jsonString = JSON.stringify(jsonObject);
console.log(jsonString);

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

javascript extract data from JSON

How can I extract values from the [object Object] in javascript? I have a JSON response from PHP that I am passing into JavaScript. I want to retrieve the GPSPoint_lat and GPSPoint_lon values. var jArray = ; var obj = JSON.parse(jArray); I am gett ...

Utilizing JQuery for a smooth animation effect with the slide down feature

I have a question about my top navigation bar animation. While scrolling down, it seems to be working fine but the animation comes with a fade effect. I would like to achieve a slide-down effect for the background instead. Since scrolling doesn't trig ...

Attempting to retrieve a URL from wunderground using Python version 3.3.2

I've been facing challenges for some time now while trying to update a piece of code from an older Python version. My aim is to do an API lookup from wunderground, but I keep running into errors in Python. Here's the specific error message: f = ...

Looking to prevent printing and saving a webpage directly from the file menu using JQUERY or JavaScript

I am in need of assistance to find a code that can disable the ability to print and save a webpage using JQUERY or JAVASCRIPT ...

Encountering a 400 error when utilizing the Google Translate free API with Curl

I am attempting to utilize the free Google Translate API that is derived from Firefox's S3 Google Translator addon, by incorporating the following code: https://translate.google.com/translate_a/single?client=t&sl=auto& tl=en&hl=en&dt= ...

Combining Multiple Arrays into a Single Array

Is there a way to combine this merge operation that creates one array using forEach into a single array at the end? affProd.pipe(mergeMap( event1 => { return fireProd.pipe( map(event2 => { const fi ...

All browsers experiencing issues with autoplay audio function

While creating an HTML page, I decided to include an audio element in the header using the code below: <audio id="audio_play"> <source src="voice/Story 2_A.m4a" type="audio/ogg" /> </audio> <img class= ...

AngularJS wildcards can be used in filters for a versatile approach

Is there a more efficient way to filter a list of values using wildcards? searchString = "ab*cd" The goal is to retrieve all values that begin with "ab" and end with "cd". One approach I've tried involves splitting the string into multiple substrin ...

A guide on integrating array map with a v-for loop in Vue

Struggling to understand how to implement a loop within another loop in Vue? This task might seem simple with React, but Vue presents its own challenges when it comes to using loops with arrays in templates/JSX. The input data follows a specific format fr ...

Error Encountered in Vue.js when Trying to Access a Nested

Below is a snippet of my route code from app.js let routes = [{ path: "/dashboard", component: require("./components/Dashboard.vue") }, { path: "/tour", component: require("./components/Index.vue"), children: [{ name: &apos ...

Using ng-class in Angular.js with a boolean retrieved from a service: A step-by-step guide

I need to dynamically set a class based on a boolean value that is determined in a service. This example is simplified for readability, but in reality, the boolean would be set by multiple functions within the service. Here is how it would look in HTML: ...

Switching between different elements in an array using React

I've got a collection of appointments and I need to create a React view that will show them one by one. Users should be able to navigate through the appointments using arrow buttons. Here's an example of what the data looks like: const arr = [ ...

Learn how to dynamically insert an element into an angular scope using a click event

Currently, I am working on a function called onGroundUserClick within the Scope passedScope. The goal is to have a function triggered upon the completion of loading the iframe that will establish ng-click. var $tdName = $("<td/>", { ...

What methods should I use to modify the upcoming array of objects?

I have been struggling with this exercise for about an hour now, and I can't figure it out. Can someone please help me with this? Here is the array that I retrieved from the database: View Base Array Image let data = [ { "name": "October : 2019", "u ...

Converting an Observable Array into a nested JSON structure

Having difficulty storing an array of information properly as JSON. A visual representation of the issue can be seen in this fiddle. Input a set of tags and check the console for output. Additional detail: An input captures a comma-separated list of tag ...

Determine whether a variable is defined following the keyup() event in jQuery

I am currently working on creating a registration form using the keyup() function in JQuery. For instance, when the input is correct, I assign it to a variable called txtuname. After pressing the register button, I need to ensure that all form variables ...

The jQuery statements are not properly executing the if and else conditions

i'm currently assessing the condition using this particular code. jQuery(document).ready(function($){ $('#uitkering_funds').hide(); $('#uitkering_funds_hoofd').hide(); $('#partner_uitkering').hide(); $('#par ...

Jersey allows for easily sending both image and JSON data together in a multipart response

Currently, I am in the process of learning Jersey by working on creating a Rest service that can receive an image from a client, process it, and then return a new image with additional information related to the processing. The uploading functionality is w ...

Permuting sentences to create intricate anagrams

I am faced with a task of creating the correct phrase for a sentence anagram using an array of nearly 2700 strings. The list consists of almost 100k words that could potentially fit. My goal is to combine these words in groups of 1, 2, and 3 words togethe ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...