Parsing a JSON string in javascript - javascript

I encountered a weird behaviour of JSON.parse method in javscript.
If you pass it a string in quotes like - "\"I am a random string\""
Instead of throwing an error it will parse the string and return the same
var a = '"I am a random string"';
var b = JSON.parse(a); // no error, parsing is successful
console.log(b); // output "I am a random string"
I am wondering what could be the cause of this? Is a string in quotes considered a valid JSON object?

According to the JSON Specification, a JSON text is any serialized value. Any of the following value types is valid JSON:
Objects ({ })
Arrays ([ ])
Strings ("a")
Numbers (1)
true, false and null
Quoting directly from the grammar in the spec:
value = false / null / true / object / array / number / string
JSON.parse() can deserialize any kind of value listed above, not just Objects.

Related

Can JSON values be numbers?

Can JSON values (not keys) be numbers, or do they HAVE to be strings only? So the following is valid.
{"number":"6"}
But is the following also valid?
{"number":6}
In JSON, 6 is the number six. "6" is a string containing the digit 6. So the answer to the question "Can json numbers be quoted?" is basically "no," because if you put them in quotes, they're not numbers anymore.
The only thing that needs to be between quotes is the property name (number).
It is valid JSON syntax. But beware that different programming languages will parse JSON differently..
https://www.freeformatter.com/json-validator.html
Json values can be
a string
a number
an object (JSON object)
an array
a boolean
null
See - https://www.w3schools.com/js/js_json_datatypes.asp

Convert Bson to Json object

Crome developer tool show this
console.log('DATA*** ', data[0]._id);
error : DATA*** Object {_bsontype: "ObjectID", id: "YIä↵P¨H0"}
How I can convert it into normal JSON object?
What you are looking for is
JSON.stringify()
JSON.stringify(objectToSerialize)
You need to use JSON.stringify() and then JSON.parse() to convert bson to valid json.
const dataString = JSON.stringify(data[0]);
const parsed = JSON.parse(dataString);
console.log(parsed._id);
Other bson types may give you its associated representation in Canonical format. For example, if you used the decimal bsonType in your mongodb it will present it like so:
...(continuing from code block above)
console.log(parsed.aDecimalNumber); // { $numberDecimal: 1.00 }
you want to call the .tostring() function on the id field.
The objectId is held as a special type stored in hex to reduce size. You'll need to use the toString function to convert it to the 24 ascii char string
https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js#L171-L179
console.log('DATA*** ', data[0]._id.toString());

Is there a way to use something equivalent to json.dumps in javascript

I am supplying a list of objects to my django template. I have a conditions where i am accessing one of the field of object in template which is a json field containing u' characters like {u'option': False, u'name': u'test string'}
We usually use json.dumps for this in python to convert this to {"option": False, "name": "test string"}, which is proper json that i want to have as i need to access such string in my javascript.
Is there a simple way to do this in javascript? I would like to avoid using regex to strip out u' and ' and replace with "
Sorry if this was very basic. Don't know much about javascript.
Or is there a way to just encode my object fields to_json somehow from python?
The equivalent to Python's json.dumps() in JavaScript is JSON.stringify() as in:
var jsonstr = JSON.stringify(someVariable);
Valid JSON doesn't contain structures like u'something', only "something". If you really have a string like that, it's likely from Python via repr() or similar.
If you're trying to convert Python objects to JavaScript objects from within their respective environments, in Python you would convert them to a JSON encoded strings using json.dumps(), transfer the strings to the JavaScript environment, and then use JSON.parse() to convert them back into objects.
(Keep in mind that JSON doesn't understand anything beyond some basic types such as string, float, boolean, array, and key:value structures. For example, trying to transfer a Python datetime object is likely to get you string or a collection key:value pairs rather than an actual JavaScript Date object.)
The difference is that json.dumps applies some minor pretty-printing by default but JSON.stringify does not, you can see below for same.
  Python:
>>> import json
>>> json.dumps({"candidate" : 5, "data": 1})
'{"candidate": 5, "data": 1}'
  Javacript:
> JSON.stringify({"candidate" : 5, "data": 1})
'{"candidate":5,"data":1}'
But with some modification, we can have the same JSON string, and to verify both are the same JSON string in formatting as well, we can generate the hash for both JSON strings and compare. There are two ways for it:-
Modifying javascript JSON string to make it equivalent to a python JSON string.
Python:
>>> import json,hashlib
>>> a = json.dumps({"candidate" : 5, "data": 1}, sort_keys=True)
>>> hashlib.md5(a.encode("utf-8")).hexdigest()
'12db79ee4a76db2f4fc48624140adc7e'
Javacript:
> const Crypto = require("crypto-js")
undefined
> const a = JSON.stringify({"candidate" : 5, "data": 1}).replaceAll(":", ": ").replaceAll(",", ", ")
undefined
> Crypto.MD5(a).toString(Crypto.enc.Hex)
'12db79ee4a76db2f4fc48624140adc7e'
Modifying python JSON string to make it equivalent to a javascript JSON string.
Python:
>>> import json,hashlib
>>> a = json.dumps({"candidate" : 5, "data": 1}, separators=(',', ':'))
>>> hashlib.md5(a.encode("utf-8")).hexdigest()
'92e99f0a99ad2a3b5e02f717a2fb83c2'
Javacript:
> const Crypto = require("crypto-js")
undefined
> const a = JSON.stringify({"candidate" : 5, "data": 1})
undefined
> Crypto.MD5(a).toString(Crypto.enc.Hex)
'92e99f0a99ad2a3b5e02f717a2fb83c2'
Note:- To run javascript code, crypto-js npm pkg should be installed as same location where you started the node shell.

In Javascript ,how to represent 1.00 as a number in a JSON object?

All I want to do is to create a JSON string like this :
'{ "a" : 1.00 }'
I have tried
var n = 1.00;
var x = { a : n };
console.log(JSON.stringify(x)); // Gives {"a":1}
var n = 1.00;
var x = { a : n.toFixed(2) };
console.log(JSON.stringify(x)); // Gives {"a":"1.00"}
var x = { x : 1.00 };
x = JSON.stringify(x , function(key,val ){
if( typeof val === "number")
return val.toFixed(2);
return val;
});
console.log(x); // Gives {"x":"1.00"}
Is it even possible to represent '{ "a" : 1.00 }' as a JSON string in javascript ?
If yes, how can I do it ?
A number in JSON doesn't have any specific precision. A number is represented as the shortest notation that is needed to reproduce it.
The value 1.00 is the same as the value 1, so that is how it is represented in JSON.
If you specifically want to represent a number in the 1.00 format, then you can't store it as a number, you would need to use a string.
The string '{"x":1.00}' is valid JSON, but it has the same meaning as '{"x":1}'.
toFixed() returns a string, and therefore will always result in "1.00" instead of 1.00.
The only way I can think of to get a JSON string with 1.00 as a value is to create it like you did above with toFixed(), then modify the string afterwards by either removing the quote characters from "1.00".
You could also create it without toFixed() and then go in and add the .00 characters.
Either way it strikes me as more effort than it's worth, but it should be possible. I can't think of a way to do it directly.
What you are trying to achieve is out of the scope of serialized object concept. Serialization is about presenting data in the most general way so both sender and the receiver of this serialized object will be able to understand in any programming language. The definition of this data type you are trying to represent is called 'Number' in JSON. You should parse or cast it to the type you need (this is part of the deserialization concept, and usually being done by the JSON parsing method).

Why is the result of adding two empty arrays in JavaScript a string?

Adding two empty arrays:
[] + []
results in an empty string. Why?
The + operator only exists for numbers and strings. When you use it on another type, JavaScript tries to convert the type (first to string, then int).
When arrays are casts to strings, they are output as comma-separated strings.
So, [] + [] => "" + "" => "".
Another example: [1,2] + [3,4] => "1,2" + "3,4" => "1,23,4"
Relevant Spec: https://tc39.es/ecma262/#sec-addition-operator-plus
In JavaScript, there are two types of value: primitives which include null, undefined, boolean, string and number; everything else is an object, including array
When adding things, JavaScript converts values to numbers, strings or primitives. Internally, JavaScript uses the toPrimitive method to convert variables to primitive.
Here is the signature of toPrimitive:
toPrimitive(input, preferedType);
With [] + [], JavaScript converts [] to a primitive, first tries valueOf() which returns the array:
var arr = [];
arr.valueOf() === arr // true
As that result is not a primitive, toString() is called and returns the empty string (string is a primitive). Therefore, the result of [] + [] is the concatenation of two empty strings.
Because the + operator serializes the two arrays and concatenates the two results. The serialization is done via the Array.prototype.toString method which basically does this:
function () { return this.join(','); }
The two arrays are empty, thus the string returned by toString is also empty and two empty strings make an empty string as well.
Speculation, but I'm guessing that JavaScript is attempting concatenation there, rather than additon.
The + operator will try to convert the array to string. Use the concat command, if you want to join two or more arrays.

Categories

Resources