I think your data array should be like this:

var data = [{
name: string,
active: bool,
data: { //Use {} instead of []
    value: number,
    date: string
  }
}]
Answer from hamed on Stack Overflow
🌐
ServiceNow Community
servicenow.com › community › developer-forum › snow-flow-how-do-we-deal-with-json-stringify-for-nested-objects › m-p › 1353839
SNOW Flow: How do we deal with JSON Stringify for nested objects?
March 27, 2022 - It is possible to nest objects. Following is a sample Script Include. Following works OK. Will need to see the actual script that being executed to find the problem. The problem seems to be .toString() somewhere that's converting an object to a string named "object" somewhere in the code. function getUserInfo(user_id) { var result = {}; result['name'] = this.getUserName(user_id); result['role'] = this.getRoleInfo(user_id); return JSON.stringify(result); } function getUserName(user_id) { var grUser = new GlideRecord('sys_user'); if (grUser.get(user_id)) { return grUser.user_name.toString(); } r
Discussions

json - Javascript Stringify Nested Objects with Loop References - Code Review Stack Exchange
The reason I don't only use JSON.stringify() is because it does not conserve the prototype, and also does not support loop references. Is this approach hacky? Is there something about the objects I duplicate that I am missing when I only duplicate its properties? More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
March 28, 2018
ajax - JSON.stringify() - nested objects - Stack Overflow
This only happens when testData contains a nested object. 2013-10-30T00:06:04.513Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... ... 0 Have an "Circular reference in value argument not supported" error with JSON.stringify... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
ajax - JSON stringify nested object - Stack Overflow
I have to send data from view to controller using ajax. Here is my class and I should send JSON appropriate to that class structure. Jackson will convert JSON to my class public class More on stackoverflow.com
🌐 stackoverflow.com
February 5, 2016
Stringying this JSON drops all elements of the nested array
There are a few misconceptions that are leading you astray. nested objects cant be stringified That is not true: JSON.stringify({ foo: { bar: 'baz' } }) //=> '{"foo":{"bar":"baz"}}' but if I just console.log the array by itself before returning, the array is correctly populated with the image data. That is because you are seeing a live representation of the object. By the time you observe it in the console, the array has been populated. Your issue is because of the asynchronicity as you had once thought. There are some solutions here . More on reddit.com
🌐 r/learnjavascript
5
5
October 25, 2023
🌐
GitHub
gist.github.com › mandrasch › 260f620c3b0d8003aec2d3ec18c44ea6
JSON.stringify with nested objects - Gist - GitHub
JSON.stringify with nested objects. GitHub Gist: instantly share code, notes, and snippets.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript - MDN Web Docs
If space is anything other than ... the given value, or undefined. ... A BigInt value is encountered. JSON.stringify() converts a value to the JSON notation that the value represents....
🌐
CodeKraft
abdulapopoola.com › 2017 › 02 › 27 › what-you-didnt-know-about-json-stringify
What you didn't know about JSON.Stringify - CodeKraft
August 14, 2021 - If the replacer is not defined, then all fields of the object will be returned – just as JSON.stringify works in the default case. For arrays, only the keys present in the replacer array would be stringified. let foo = { a : 1, b : "string", c : false }; JSON.stringify(foo, ['a', 'b']); //"{"a":1,"b":"string"}" Arrays however might not be as flexible as desired, let’s take a sample scenario involving nested objects.
Find elsewhere
🌐
GitHub
gist.github.com › davidfurlong › 463a83a33b70a3b6618e97ec9679e490
JSON.stringify replacer function for having object keys sorted in output (supports deeply nested objects) · GitHub
JSON.stringify replacer function for having object keys sorted in output (supports deeply nested objects) - JSON.stringify-replacer-sort-keys.js
🌐
Reddit
reddit.com › r/learnjavascript › stringying this json drops all elements of the nested array
r/learnjavascript on Reddit: Stringying this JSON drops all elements of the nested array
October 25, 2023 -

Hello all, this is my first ever reddit post so please bare with me.

I am having an issue when trying to stringify a json that contains an array of jsons.

Here is the code:

function addImages(imageArr, values){
//Declare an empty array of images
var images = []

//For each image object in the image array
for(var image of imageArr){
    //Create a new file reader
    const reader = new FileReader();
    //Read the base64 data from the image
    reader.readAsDataURL(image);
    reader.onload = function () {
        //Creat a json with the name of the image and the
        //base64 data of the image
        var imageJSON = {
            "name" : image.name,
            "content" : reader.result
        }
        //Push that json to the image array
        images.push(imageJSON);
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
}
//create a json to hold the entire list of images
const imageListJSON = {
        //When i stringify the array, the result is always "[]"
    "images" : JSON.stringify(images)
}
//merge this image list with values, a json containing user data
const userData = {...values, ...imageListJSON};
return userData;

}

(For context, the imageArr parameter is an array of Web API file objects that are all of either png, jpg, or jpeg images)

The issue is, when i post this data to my backend, all the elements of the image array are dropped. I discovered this was because under the hood, they are stringified and nested objects cant be stringified. I have tried in numerous ways to solve this:

  • Stringify the imageJSON before pushing it to the images array (this correctly stringifies the jsons in the array)

  • Stringify the images array when I put it in the imageListJSON (you can see this in my code, the resulting string is always "[]")

  • Stringify the entire imageListJSON before merging it with values into userData (the resulting string is something like "/"images/" : /"[]/"")

  • Every permutation of the previous items.

If anyone can help me out with this, it'd be greatly appreciated. If you need more context, let me know and I will give it to you. I wanted to upload some images of the output but it isn't letting me upload images for some reason.

Thanks

EDIT: Figured I would add this as well, I thought it might be because the reader function is asynchronous and maybe the data wasn't being put into the array at all before it was being stringified, but if I just console.log the array by itself before returning, the array is correctly populated with the image data. It is only when i stringify it that all the elements get dropped.

Top answer
1 of 2
3

If you're willing to go to the effort of whitelisting, then you can establish an array of valid keys, which can provide the ability to nest similar to how many systems do JSON nesting (a . separator, or any separator of your choosing).

var whitelistedObj = whitelistJson(obj, ["company_name", "example", "address.street", "address.example"]);

function whitelistJson(obj, whitelist, separator) {
    var object = {};

    for (var i = 0, length = whitelist.length; i < length; ++i) {
        var k = 0,
            names = whitelist[i].split(separator || '.'),
            value = obj,
            name,
            count = names.length - 1,
            ref = object,
            exists = true;

        // fill in any empty objects from first name to end without
        //  picking up neighboring fields
        while (k < count) { // walks to n - 1
            name = names[k++];
            value = value[name];

            if (typeof value !== 'undefined') {
                if (typeof object[name] === 'undefined') {
                    ref[name] = {};
                }

                ref = ref[name];
            }
            else {
                exists = false;
                break;
            }
        }

        if (exists) {
            ref[names[count]] = value[names[count]];
        }
    }

    return object;
}

I have a JSFiddle showing its usage as well (to ensure it actually worked on my admittedly small sample set).

2 of 2
2

You can add toJSON method in your huge JSON objects:

var test = {
    "company_name": "Foobar",
    "example": "HelloWorld",
    "address": {
        "street": "My Street 12",
        "example": "BarFoo",
        "details": "Berlin",
    },
    toJSON: function () {
        return {
            company_name: this.company_name,
            address: {
                street: this.address.street,
                example: this.address.example
            }
        }
    }
}

And, you get:

console.log(JSON.stringify(test)); // "{"company_name":"Foobar","address":{"street":"My Street 12","example":"BarFoo"}}"

Or, you can use some filter function: (this function using lodash)

function filter(object, keys, sep) {
    sep = sep || '.';
    var result = {};
    _.each(keys, function (key) {
        var keyParts = key.split(sep),
            res = object, 
            branch = {},
            branchPart = branch;

        for (var i = 0; i < keyParts.length; i++) {
            key = keyParts[i];
            if (!_.has(res, key)) {
                return;
            }

            branchPart[key] = _.isObject(res[key]) ? {} : res[key];

            branchPart = branchPart[key];
            res = res[key];
        }

        _.merge(result, branch);
    });
    return result;    
}
console.log(JSON.stringify(filter(test, ['company_name', 'address.street', 'address.example']))); // "{"company_name":"Foobar","address":{"street":"My Street 12","example":"BarFoo"}}"

Check out jsfiddle http://jsfiddle.net/SaKhG/

🌐
ProxiesAPI
proxiesapi.com › articles › convert-object-to-json-string-in-javascript
Convert Object to JSON String in JavaScript | ProxiesAPI
October 4, 2023 - Here are some key things to understand about JSON in JavaScript: ... Array.isArray(). Since objects can be nested, we need to recursively stringify nested values.
🌐
Stack Overflow
stackoverflow.com › questions › 73666162 › json-stringify-not-stringifying-nested-objects
JSON.stringify() not stringifying nested objects
Everything is working except for the JSON.stringify(). I thought maybe it might have been a special character so my test data is replaced with just a character (attached below). The subs nested objects in object 1 and 9 don't want to come over through the stringify.
🌐
DEV Community
dev.to › iamcymentho › demystifying-nested-data-a-guide-to-accessing-and-processing-objects-arrays-and-json-in-javascript-34im
Demystifying Nested Data: A Guide to Accessing and Processing Objects, Arrays, and JSON in JavaScript - DEV Community
September 15, 2023 - Configuration Files:Reading configuration settings from JSON files. User Profiles: Managing user profiles with nested attributes. ... Use Destructuring: Use object destructuringto simplify access to nested data. Error Handling: Implement error handling for unexpected data structures. ... Circular References: Be cautious of circular references when stringifying objects to JSON.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
JSON methods, toJSON
The third argument of JSON.stringify(value, replacer, space) is the number of spaces to use for pretty formatting. Previously, all stringified objects had no indents and extra spaces. That’s fine if we want to send an object over a network. The space argument is used exclusively for a nice output. Here space = 2 tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces inside an object:
🌐
CodeSandbox
codesandbox.io › s › recursion-stringify-nested-object-toc48
recursion: stringify nested object - CodeSandbox
May 12, 2020 - recursion: stringify nested object by neljson
Published   May 10, 2020
Author   neljson
🌐
GitHub
github.com › trentm › node-bunyan › issues › 492
Deeply nested [Objects] and how to stringify them. · Issue #492 · trentm/node-bunyan
April 12, 2017 - And despite it being an object, it doesn't turn out as strictly legal JSON but the loose style of JSON with linebreaks? What I end up having to do is JSON.stringify(span.toJSON()) and send that string to bunyan, which results in an extra ugly string encoding.
Author   trentm