Inject scope of a function into JSON.parse - json

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

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.

Related

How to export JSON-like data in spreadsheet column to json file?

I have a Google sheet with JSON-like data in a column and would like to export this column as a JSON file. I have tried using javascript along with xlsx package to convert the sheet to json file but it adds backslashes to the column and cannot be parsed (throws syntax error) using JSON.parse() as it does not recognise it as valid json. Any help is appreciated!
let xlsx = require("xlsx")
let path = require("path")
let fs = require("fs");
const inputFilePath = path.join(__dirname, './Sample.xlsx');
let File = xlsx.readFile(inputFilePath);
let content = xlsx.utils.sheet_to_json(File.Sheets['Sheet1']);
console.log(JSON.parse(content[0]["content"])); //throws error
Here is an example that will write the data without backslash (do not use JSON.stringify in this case). The file will be in 'test' folder here, that you have to create or change in the script.
// you need to activate the Advanced Drive Service (Drive Activity API).
function test() {
var content = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('A1').getValue();
var folders = DriveApp.getFoldersByName("test");
if (folders.hasNext()) {
var folder = folders.next();
saveData(folder, 'myJSON.json',content);
}
}
function saveData(folder, fileName, content) {
var children = folder.getFilesByName(fileName);
var file = null;
if (children.hasNext()) {
file = children.next();
file.setContent(content);
} else {
file = folder.createFile(fileName, content);
}
}
https://docs.google.com/spreadsheets/d/1PWzdlaZi2m0a1xDiqLp2eJXIvx-AyvZ16CQW362q-Nw/edit?usp=sharing
Of course, replace A1 by B2 for your file.

JSON Query in Google Sheets/Scripts

I am importing data from a JSON file using Google Apps Script and Google Sheets. I have learned the basics on this, but the formatting on the JSON file I am attempting to parse is throwing me off.
What is confusing me is how I would search for information based on "name". Currently I am using this:
function JSONReq(url, xpath){
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var json = JSON.parse(content);
var patharray = xpath.split("/");
for(var i = 0; i < patharray.length; i++){
json = json[patharray[i]];
}
return json;
}
I'm a bit lost now to be honest with you.
I want to have a cell where I can type a name that I already know of, then find it in the JSON file and pull the return that information however I decide to do it. I can pull and write to cells, I have the basics down. But I just can't understand how I could search by the name.
That JSON file is an array of objects. To find a specific object with a given "name", you would parse it into an object (which you do already), then iterate through them and check the name parameter:
var myName = "name of thing I want";
var arr = JSON.parse( ... );
for(var i = 0; i < arr.length; ++i) {
var obj = arr[i];
if(obj.name == myName) { // could be done as obj["name"] == ... too
// do stuff with obj
}
}
For your case, you might add an additional argument to your function (i.e. 2nd arg = the object's property, e.g. "name", with the 3rd = the desired value. This will be fine for any simple key-value properties, but would need specific handling for where the value is itself an object (e.g. the "category" field in your specific JSON file).

Uncaught SyntaxError, Unexpected Identifier in for loop in jade

I am trying to render a jade with some dynamic content. I am reading from a json in jade.
My json looks like this
{ data1: 'data1',
data2: 'data2',
data3:
[ { name: 'ABC',
address: 'India'
},
{ name: 'DEF',
address: 'Australia'
}]}
I am trying to render a jade and use the data from above json
my jade looks like
var data1 = #{data1};
var data2 = #{data2};
var size = #{data3.length};
for data in #{data3}
var name = data.name;
var address = data.address;
I am able to correctly extract data in the first 3 lines mentioned above. But when I try to fetch data from within a loop, I get "Uncaught SyntaXError, Unexpected Identifier" error while debugging.
If i put a line outisde the for loop, it works fine. Ex
var name = #{data3[0].name};
is rendered properly. But i need to iterate over a loop and fetch data over there. Can somebody help.
Thanks
Updating with more information
1. I have node server running where I create a json -
var json_string = "{"data1":"data1","data2":"data2","data3":[{"name":"ABC","address":"India"},{"name":"DEF","address":"Australia"}]};";
var json_data = JSON.parse(json_string);
console.log(json_data);
res.render('sample_example', json_data);
In my sample_example.jade I have the following snippet within script
var data1 = #{data1};
var data2 = #{data2};
var size = #{data3.length};
for data in #{data3}
var name = data.name;
var address = data.address;
As stated earlier, I am able to properly extract #{data1}, #{data2}, #{data3.length} to the variables . But it breaks within the for loop. In fact, I am able to extract #{data3[0].name} from outside the for loop. But within the for looop it gives the stated error.
This is how you can do it now.
In your server-side you have to JSON.stringify the array of objects.
var json_data = JSON.parse(json_string);
// Convert back to json only the property data3
json_data.data3 = JSON.stringify(json_data.data3);
res.render('simple', json_data);
Or the better is to not parse the JSON just let it go the way it is:
// var json_data = JSON.parse(json_string);
res.render('simple', {
json_data: json_string
});
And in the Jade Template (If you followed the better method):
script(type='text/javascript').
var json_data = !{json_data};
var data1 = json_data.data1;
var data2 = json_data.data2;
var data3 = json_data.data3;
var size = data3.length;
data3.forEach(function(data) {
var name = data.name;
var address = data.address;
console.log(name, address);
});
Also you need to change the loop structure. The for..in used to iterate over objects not array of objects.
This works for me;
- var cdata = {"data1":"data1","data2":"data2","data3":[{"name":"ABC","address":"India"},{"name":"DEF","address":"Australia"}]};
each data in cdata.data3
- var name = data.name;
- var address = data.address;
p Name: #{name}
p Address: #{address}
Can you share the actual jade file contents if updating the code as shown above doesn't work. Also what version of jade and express?

How to iterate through the files in a folder - Part II?

I wrote this code to iterate from the files of a folder:
function showList() {
var folder = DocsList.getFolderById('0B9HEC6UUJ_rsYWNPYko0MsrBRU0');
var files = folder.getFiles();
Logger.log("files = " + files);
arrayList = [];
for (var file in files) {
Logger.log("file = " + file);
var fileName = file.getName();
var fileId = file.getId();
var newArray = [fileName, "some info", fileId];
arrayList.push(newArray);
}
But in this line var fileName = file.getName();, I got this error: TypeError: Cannot find function getName in object 0.
The logs show this:
It seems there are files, but not the file that should get in the for loop. How to fix that?
Many problems in your js code:
1) thats not how you use 'in' in js. File will be an index so you need to do files[file]
2) even then its still wrong because iterating an array with 'in' will give you other things like the 'length' property.
Look up in the web how to iterate a js array.

Action Script 3.0 : parsing json data

I want to parse the json data shown in this link in AS3 to obtain the "message" field . I am trying with
as3corelib.swc with no success. The json data seems to be bit different . Please help me to parse this
I am using the below code
var j:Object = JSON.decode(Json_data);
var message:String = j["message"];
trace(message);
Here trace always showing null
There is no message under root object. Probably you are looking for this:
var j:Object = JSON.decode(str);
var data:Array = j["data"];
for (i = 0; i < data.length; i++) {
trace(data[i].message);
}