Categories
JavaScript Answers

How to fix JSON.stringify not working with normal JavaScript array?

Spread the love

Sometimes, we want to fix JSON.stringify not working with normal JavaScript array.

In this article, we’ll look at how to fix JSON.stringify not working with normal JavaScript array.

How to fix JSON.stringify not working with normal JavaScript array?

To fix JSON.stringify not working with normal JavaScript array, we should make sure arrays have all numerical keys.

For instance, we write

const test = {};
test.a = "test";
test.b = [];
test.b.push("item");
test.b.push("item2");
test.b.push("item3");
const json = JSON.stringify(test);
console.log(json);

to create array properties a and b.

And we call push to push contents into it.

Then we call JSON.stringify to return the test object converted to a JSON string.

Conclusion

To fix JSON.stringify not working with normal JavaScript array, we should make sure arrays have all numerical keys.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *