最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert Bson to Json object - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Feb 12, 2020 at 9:57 Pushprajsinh Chudasama 7,9794 gold badges23 silver badges48 bronze badges asked May 17, 2017 at 13:06 Roman PawliwRoman Pawliw 571 gold badge3 silver badges7 bronze badges 1
  • Have you looked into bsondump? – evolutionxbox Commented May 17, 2017 at 13:08
Add a ment  | 

3 Answers 3

Reset to default 2

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./mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js#L171-L179

console.log('DATA*** ', data[0]._id.toString());
发布评论

评论列表(0)

  1. 暂无评论