JSON.stringify() result when input is single value - javascript

The JSON.stringify() method converts a JavaScript value to a JSON
console.log(JSON.stringify('a'));
//produce "a"
console.log(JSON.stringify(1));
//produce 1
console.log(JSON.stringify(true));
//produce true
but according to the definition these are not JSON
"a"
1
true
JSON definition is showing below
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
my question is JSON.stringify() not producing JSON when input above values why is that ?

The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
Ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
"my question is JSON.stringify() not producing JSON when input above values why is that?"
These are all Valid JSON syntax representing JSON value:
"a"
1
true
{}
[]
Check this:
JSON.parse('"foo"'); // returns "foo"
JSON.parse(1); // returns 1
JSON.parse(true); // returns true
JSON.parse('{}'); // returns {}
JSON.parse('[]'); // returns []
For more clarification this check these answers:
Is this simple string considered valid JSON?
What is the minimum valid JSON?

Related

Are array keys implicitly coerced to numbers?

I'm in the book, This & Object Prototypes, Chapter 3: Objects.
In the arrays section, the author says if you add a property to an array, but the array looks like a number, it will end up as part of the array index:
myArray["3"] = "baz";
console.log(myArray.length);
console.log(myArray[3]);
It looks like JavaScript is implicitly coercing the "3" string into the number 3, then it's saying place "baz" in index 3 of the array.
Actually, it's the other way around. All keys in JavaScript objects are strings, and arrays are objects. That means myArray[3] is the same as myArray["3"] because all keys, if not already strings, are coerced into strings because all JavaScript object keys are strings. Per MDN:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string.
And:
Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type. For example, in the above code, when the key obj is added to the myObj, JavaScript will call the obj.toString() method, and use this result string as the new key.
For example:
const obj = {
toString() {
return 'foobar';
}
};
const anotherObj = {};
anotherObj[obj] = 'baz';
//anotherObj.foobar is now 'baz'
Since obj is converted to a string implicitly, obj.toString is called which returns 'foobar', which is used as the key value. The same applies for arrays -- when using bracket notation. All keys are strings, and accessing using bracket notation coerces the expression in the brackets into a string.

Why console.log in node.js doesn't print array correctly while util.inspect does

The following two lines produce the following output:
console.log('arr:'+arr);
console.log('inspected arr:'+util.inspect(arr));
arr:,testUser2
inspected arr:[ null, 'testUser2' ]
is it because it starts with a null value? it is very confusing that it doesn't even show up as an array.
it is in fact an array though!
That is because you have null in array and when you say
"somestring" + array
it converts array to string using toString(), so null will be converted to "".
just try in browser console [null,1,2].toString() it will print ",1,2".
While Util.inspect returns a proper string representation of the object. Where it will print every thing as string something like JSON.stringify().
JS's occasionally-wat coercion rules.
Once you coerce it to a string the brackets go away, and a null value is represented by zero characters. inspect is the proper way to specify you want it to print out it's "natural" representation.
Well, the empty string when you try to print out the array if the value is null in the array is right as per specification in ECMAScript here
when you try to concat the array like that, actually what you do is that you implicitly call the toString function in the array object which will call the join function in array object. And, in join spec, the function should check the null value, if null then it should return empty string.
This is taken from documentation.
If element0 is undefined or null, let R be the empty String; otherwise, let R be ToString(element0).
in your case, I guess it will be much better to use util.inspect() as it does print more "pretty" information.

What is the type of the Value that can be inputed in a JSON Array / Object?

Knowing that, in JSON format, the Object and the Array structures can contain respectively pairs of name/value and ordered collection of values and that the values can be object/array/string/number/true/false/null ; is it correct to say that in an array (or in an object) the type of value can vary ?
Meaning by that that i can have for example this array :
[String,Number,Array,Array,Object] or it must be this way [String,String,...] or [Array,Array,...] (same type of value all over the array)
Same question for the object structure. (concerning the value part of the pair keyname/value)
Yes, you can associate any type of value with any property of another object, and you can add any type of value into an array.
For example, this is perfectly valid JSON:
{
"key1": 1,
"key2": "Two",
"key3": ["Three", 4, {"five": "six"}, ["seven"]]
}
... which can be used to define a value, as you see here:
In Javascript the type of elements in an array can vary. For example
var a = ["hello", 12345, {key : "value"}, true];
This is valid javascript. However it is bad practice to have more than one type in an array as you have to know the order of the expected element to access them. e.g. you have to know that the first element is a string.
It would be better to represent the above array as an object with named properties:
var o = {
aString : "hello",
aNumber : 12345,
aSubobject : {
key : "value"
},
aBool : true
}
Array by definition should contain only the elements of the same type.
The object however may contain different element types. This is the basic assumption in JSON.
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

array and object confusion in json

what is the different between is
var json = [{
'id':1,
'name':'John'
}]
and
var json = {
'id':1,
'name':'John'
}
my understanding is that in code one json is an array, which means we can have multiple object which contains property of id and name. But for the second one it's an object. Is it?
and how about this one
var json = ['id':1,'name':'John']
compare to code one?
Nothing is valid JSON in your case.
The first one is an array of native javascript objects.
The second one is a javascript object.
The last one isn't valid and will throw error. It is syntactically wrong.
Use JSON.stringify() on javascript arrays or objects to make it a valid JSON.
You understanding about code one and code two are correct.
But however, the json syntax about code one and two is error. Because each json field must use double quotes, not single quotes.
so code one and code two must be written like this:
[
{
"id": 1,
"name": "John"
}
]
and
{
"id": 1,
"name": "John"
}
Now code three's syntax is error! If you want to mean an array, it must be var json = []; json['id']=1; json['name']='John'; or an object var json={'id':1,'name':John'}
JSON is a format, i.e. a way to encode Javascript objects to a sequence of characters.
Once you have a sequence of characters you can store it on disk or send it over a network and later rebuild the objects described in the sequence of characters.
You cannot encode every possible Javascript value in JSON, but only
strings
numbers (excluding NaN and infinity)
null
arrays
other objects (just the fields with values that can be encoded, not the constructor or methods)
Also, the data structure must be a tree. (You get an error if it has loops, and shared sub-trees are not detected and will be duplicated when rebuilding from JSON.)
Moreover JSON doesn't support is the presence of other fields in arrays (something that is possible in Javascript, because arrays are objects). For JSON, you have either an array or an object.
The values in your first two examples can be converted to JSON, but there are additional requirements in the format specifications. (E.g. object field names must be double quoted.)
Your last example instead is not a valid JSON string.
When you see "JSON object" or "JSON value" you must read it as "object encoded in JSON". JSON is a format, more or less like XML.

Second argument in JSON.stringify in JavaScript

In JavaScript's JSON.stringify() function, I occasionally see the following syntax:
JSON.stringify(obj, null, 4)
However, I can't get what the second argument, null, is supposed to do. As long as I know, the above function takes an object as its first argument, and converts it to a string variable. The third argument, 4 in this case, indents and pretty-prints the resultant string object. But I can't see what the second argument tries to do even after I read the explanation on the official document... So what does the argument do? Or is it just there in order to take in the third argument? (But I think then the function should take both argument name and its parameter, such that for example, JSON.stringify(obj, space=4). I'm not sure whether that sort of syntax is allowed in JavaScript, so forgive me if it's not. But I don't know my expectation is correct in the first place, so would like to throw a question anyway).
Thanks.
The second parameter can be a function to perform replacement while stringifying.
A null or undefined second parameter means that you want to use standard
stringification, without any customization.
From https://developer.mozilla.org/en-US/docs/Using_native_JSON#The_replacer_pa
Starting in Firefox 3.5.4, JSON.stringify() offers additional
customization capabilities through the use of optional parameters. The
syntax is:
jsonString = JSON.stringify(value [, replacer [, space]])
value The JavaScript object to convert into a JSON string.
replacer A function that alters the behavior of the stringification process, or
an array of String and Number objects that serve as a whitelist for
selecting the properties of the value object to be included in the
JSON string. If this value is null or not provided, all properties of
the object are included in the resulting JSON string.
space A String or Number object that's used to insert white space into the output
JSON string for readability purposes. If this is a Number, it
indicates the number of space characters to use as white space; this
number is capped at 10 if it's larger than that. Values less than 1
indicate that no space should be used. If this is a String, the string
(or the first 10 characters of the string, if it's longer than that)
is used as white space. If this parameter is not provided (or is
null), no white space is used. The replacer parameter
The replacer parameter can be either a function or an array. As a
function, it takes two parameters, the key and the value being
stringified. The object in which the key was found is provided as the
replacer's this parameter. Initially it gets called with an empty key
representing the object being stringified, and it then gets called for
each property on the object or array being stringified. It should
return the value that should be added to the JSON string, as follows:
If you return a Number, the string corresponding to that number is
used as the value for the property when added to the JSON string. If
you return a String, that string is used as the property's value when
adding it to the JSON string. If you return a Boolean, "true" or
"false" is used as the property's value, as appropriate, when adding
it to the JSON string. If you return any other object, the object is
recursively stringified into the JSON string, calling the replacer
function on each property, unless the object is a function, in which
case nothing is added to the JSON string. If you return undefined, the
property is not included in the output JSON string. Note: You cannot
use the replacer function to remove values from an array. If you
return undefined or a function then null is used instead.
Example
function censor(key, value) {
if (typeof(value) == "string") {
return undefined;
}
return value;
}
var foo = {foundation: "Mozilla",
model: "box",
week: 45,
transport: "car",
month: 7};
var jsonString = JSON.stringify(foo, censor);
The resulting JSON string is {"week":45,"month":7}.
If replacer is an array, the array's values indicate the names of the
properties in the object that should be included in the resulting JSON
string.
There is no way to pass third parameter without passing second parameter in JavaScript.
So null is a placeholder for replacer function when you need to pass space.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
JSON.stringify(value[, replacer[, space]])
replacer A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
The replacer parameter can be either a function or an array.
As a function, it takes two parameters: the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter.
Initially, the replacer function is called with an empty string as key representing the object being stringified. It is then called for each property on the object or array being stringified.

Categories