binarymax binarymax - 1 year ago 66
JSON Question

Inject scope of a function into JSON.parse

I have a bunch of JSON files that I need to parse (in node), but many of the files have things like this:

"_id" : NumberLong(528000021)

is a function out of scope of the JSON file. When I run JSON.parse I get an error (understandably) that it found an unexpected token. Is there a way to create a function NumberLong and inject it into the scope of the parse?


Gave @Svabael the answer karma on this one, but for the curious here is how I ended up solving the problem. I created GLOBAL functions for any function appearing in the "JSON", and then created a module then required it.

#!/usr/bin/env node

var fs = require('fs');

GLOBAL.ISODate = function(x){return x};
GLOBAL.NumberLong = function(x){return x};

var source = "./JSONFiles/";
var target = "./JSONModules/";

for(var i=2;i<process.argv.length;i++) {
var fn = process.argv[i];

var sn = source + fn;
var sd = fs.readFileSync(sn,'utf8');

var tn = target + fn.replace('.json','.js');
var td = "module.exports = " + sd;


var json = require(tn);

//json now has the data


To call the script above it is a bash one-liner:

ls JSONFiles | xargs ./json2modules.js

Answer Source

This is not a valid JSON:

    "_id" : NumberLong(528000021)

This is a valid JSON:

    "_id" : "NumberLong(528000021)"

I think that you are trying to parse a javascript object and the error that you have is normal. If this is the case, then you don't need to parse it at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download