简体   繁体   中英

How to use JSON2 in Node.js

I want to use json2 as JSON.parse in node.js, (forgive the stupid question) I can't quite figure out how to use it. I have a copy of json2.js, with the first line removed in my current working directory. Then, from the node.js shell i do:

> orig_func = JSON.parse
[Function: parse]
> require('json2')
{ JSON: {} }
> orig_func === JSON.parse
true

I thought from the comments in the code that by requiring the file it would override the current global JSON object.

json2 checks for the existence of the JSON object before it overrides it. To use json2 you'd need to do something like

var oldJSON = JSON;
JSON = undefined;
require('json2');
JSON.stringify = oldJSON.stringify; // assuming you want builtin stringify

But note that the JSON implementation in json2.js is not 100% correct, is much slower than the builtin impl, and is less secure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM