Convert Bson to Json object - javascript

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());

Related

alternative to JSON.parse() for maintaining decimal precision?

I'm calling JSON.parse() to parse a JSON string which has small decimals.
The precision of the decimals is not being maintained after parsing. For example, a value like 3.1e-7 is being returned instead of the actual decimal.
How can I deserialize a JSON string in ng2+ while maintaining decimal precision?
UPDATE
I was thinking about mapping out the values from the string and then setting the values manually to the object after JSON.parse() but when I set a different small decimal number as a property value, the same number formatting occurs. So is this problem not necessarily unique to JSON.parse() but to Javascript in general? Or does JSON.parse() somehow configure property types in a fixed way?
As soon as you pass your JSON string through JSON.parse, you'll lose precision because of the way floating point math works. You'll need to store the number as an object designed for storing arbitrary-precision numbers, and you'll need to fiddle with the string itself before parsing it. The simplest way is with regexes. JSON is a context free grammar, and regexes work on regular grammars, so the warning applies:
WARNING: PARSING CFG WITH REGEX MAY SUMMON ZALGO
This regex should turn the numbers in your JSON into strings:
let stringedJSON = origJSON.replace(/:\s*([-+Ee0-9.]+)/g, ': "uniqueprefix$1"');
But I haven't tested it extensively and it definitely will screw things up if you have keys that are something like data:42.
Assuming it worked correctly, stringedJSON should now be something like {"foo": "uniqueprefix0.00000017", "bar": "an actual string"}. You can parse this with JSON.parse without losing precision, but uniqueprefix0.00000017 isn't what you want. JSON.parse can be called with an extra reviver argument, which transforms values passed to it before returning them. You can use this to convert your data back into a useful form:
let o = JSON.parse(stringedJSON, (key, value) => {
// only changing strings
if (typeof value !== 'string') return value;
// only changing number strings
if (!value.startsWith('uniqueprefix')) return value;
// chop off the prefix
value = value.slice('uniqueprefix'.length);
// pick your favorite arbitrary-precision library
return new Big(value);
});

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

Parsing a JSON string in 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.

Most efficient way to retrieve numbers from a querystring?

I need to parse querystrings that contain both text and numbers. For example the following querystring:
?userID=12&team=Sales&quarter=Q1&count=2310
should be translated into the following JavaScript object:
{
userID:12, // not "12"
team:"Sales",
quarter:"Q1",
count:2310 // not "2310"
}
Currently I am doing it in two steps:
Parse the querystring
Go through all the parameters and identify which ones are numbers (either with a regex or an isNumber function !isNaN(parseFloat(n)) && isFinite(n)
This seems rather inefficient especially as most of my parameters are not numbers. Is there a better way?
do you know where are you going to use the specify value?
Because if you multiplying any string in number format like "3239" by 1 this will convert that string in number..
var example = 5 + (o.count*1) //o.count will be a number...
Two suggestions:
If you know which parameters are going to hold numbers, only do the conversion for those
The fastest way to convert strings to numbers as far as I know is to use the unary operator on them, as follows:
+(strVar)
Also multiplying by 1 is supposed to be fast AFAIK
After you parse the querystring you can convert those string representations of integer value to an actual integer like this:
var obj; // your object that the string is parsed into, with all values as strings.
for (var prop in obj) {
if (String(parseInt(obj[prop])) === obj[prop]) {
obj[prop] = parseInt(obj[prop]);
}
}

JavaScript Date object not working with string passed to it

I am trying to create a date object by using a variable obtained from a database. The string is already in the correct format, already comma delimited "yyyy,mm,dd,hh,mm,ss". However trying to create a Date object returns an Invalid Date error.
var foo ='2012,03,09,12,00,00,00';
document.write(foo); //<-- obviously writes the string 2012,03,09,12,00,00,00 to the browser
var then=(new Date(foo));
document.write(then); //<-- returns Invalid Date
I have a solution which is the following:
var x = foo.split(/[,]/);
var then = new Date(x[0], x[1], x[2], x[3], x[4], x[5]);
Wondering why this is needed when essentially it's recreating the same string that was passed to it.
It's because the string you are trying to convert into a Date object is not valid. The Date object doesn't just accept any format as a string. if it is not recognised it wont work.
See Date doc https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Here is information about format supported
https://www.rfc-editor.org/rfc/rfc2822#page-14
"yyyy,mm,dd,hh,mm,ss" is not a "correct format" for a date string.
The JavaScript Date object can only parse specific formats. Check the MDN docs for Date for valid dateStrings. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Anyway. your 2nd example works because you're not recreating the string, you are are passing 6 different parameters compared to one long one.
You can't pass a comma-separated string to a function and expect it to break it into parameters, it doesn't work that way.

Categories

Resources