binarymax binarymax - 1 month ago 9
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)


Where
NumberLong
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?

--EDIT--

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;

fs.writeFileSync(tn,td);

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

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.

Comments