Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JSON.stringify() returns empty result for some objects

Tags:

javascript

This question is so basic, yet I have no idea of the answer.

Why screen object when stringified returns empty?

Does this mean JSON.stringify() needs read/write access to the input?

let a = {foo: 'one', bar: 2};


console.log(JSON.stringify(a));
console.log(JSON.stringify(screen));
like image 995
Lemures Avatar asked Jul 27 '18 11:07

Lemures


People also ask

Does JSON Stringify work on objects?

JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans.

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.

How do I check if JSON Stringify is empty?

If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }

What is the purpose of JSON Stringify () and parse () methods?

The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.


1 Answers

FROM MDN Network

For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.

Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable

    console.log((window.screen));
    console.log(JSON.stringify(window.screen));
    console.log(window.propertyIsEnumerable(screen));
like image 76
Kapil Tiwari Avatar answered Oct 02 '22 09:10

Kapil Tiwari