Using gruntjs, how would I get data from "nested" json files? - json

Let's say in my Gruntfile I have pkg: grunt.file.readJSON('package.json'), and inside the package.json is the following object:
{
"file": "data.json"
}
How would I access the data from data.json? Which might look something like this:
{
"name": "Jon Schlinkert",
"company": "Sellside"
}

Just load the first file, then use the result of that to load the second file and add it to the grunt config. Like this:
module.exports = function (grunt) {
var pkg = grunt.file.readJSON('package.json');
grunt.initConfig({
pkg: pkg,
data: grunt.file.readJSON(pkg.file),
task: {
target: {
files: {
'dest': '<%- data.name %>'
}
}
}
});
grunt.registerMultiTask('task', function() {});
console.log('name', grunt.config('data.name'));
};

Maybe I don't understand the problem, but what about:
var pkg = grunt.file.readJSON('package.json');
var data = grunt.file.readJSON(pkg.file);

Related

How to replace Filenames inside my manifest.json File using rev-replace

i'm stuck a little - i want to replace image file names with their hashed version inside my manifest file.
Manifest looks like this:
{
"icons": [
{
"src": "android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
I want those icon src to be replaced with the hashed filenames which looks like this: "android-chrome-192x192-b03df0131.png"
My gulp file which should do it looks like this:
const gutil = require('gulp-util');
module.exports = function (gulp, plugins) {
return function () {
const manifest = gulp.src('public/dist/rev-manifest.json');
return gulp.src(['public/dist/#(css|js)/**','public/dist/img/icon/**.json'])
.pipe(plugins.revReplace({replaceInExtentions: ['.json']}))
.pipe(plugins.revReplace({manifest: manifest}))
.pipe(gulp.dest('public/dist'));
};
};
after a lot of googling and Documentation reading i got it working :D
So if someone searches for this:
const gutil = require('gulp-util');
module.exports = function (gulp, plugins) {
return function () {
const manifest = gulp.src('public/dist/rev-manifest.json');
function replaceIconPath(filename) {
if(filename.includes('android-chrome-')) {
return filename.replace('img/icon/', '');
}
return filename;
}
return gulp.src('public/dist/#(css|js|img)/**')
.pipe(plugins.revReplace({
replaceInExtensions: ['.json', '.css', '.js', '.html', '.hbs'],
manifest: manifest,
modifyUnreved: replaceIconPath,
modifyReved: replaceIconPath
}))
.pipe(gulp.dest('public/dist'));
};
};
So let me explain this shortly - the important part is in plugins.revReplace.
You need the option replaceInExtension and add '.json' but you also need to specify the default options or else they will be lost.
The 'modifiyUnreved' and 'modifyReved' options are just needed if you have to modify the filenames further. In my case it couldn't find the file because my rev-manifest was on another level compared to my manifest file. So i needed to cut the path for it to find the src and replace it.

It Shows value as undefined in webpage when i enter value from JSON file, Any idea?

It Shows value as undefined in webpage when i enter value from JSON file, Any idea?
JSON FILE:
[
{
"firstName":"1233232322",
"lastName":"ramakrishnan",
"email":"parthiramkrish#gmail.com",
"password":"secondmay1991",
"confirmPassword":"secondmay1991"
}
]
SPEC FILE:
'use strict';
browser.ignoreSynchronization = true;
var testdata1 = require('./testdata1.json');
describe("Test the inksoft.com create an account page", function () {
it("enter the account details", function () {
browser.get("https://qa.inksoft.com/EGT");
browser.ignoreSynchronization = true;
browser.sleep(15000);
element(by.xpath("//a[text()='Create Account']")).click();
browser.sleep(20000);
element(by.xpath("//input[#name='firstName']")).sendKeys( testdata1.firstName);
element(by.xpath("//input[#name='lastName']")).sendKeys( testdata1.lastName);
element(by.xpath("//input[#name='email']")).sendKeys( testdata1.email);
element(by.xpath("//input[#name='password']")).sendKeys( testdata1.password);
element(by.xpath("//input[#name='confirmPassword']")).sendKeys( testdata1.confirmassword);
element(by.xpath("//input[#type='submit']")).click();
});
});
CONF FILE:
exports.config = {
//The address of a running selenium server.
seleniumAddress: 'http://localhost:4444/wd/hub',
//Here we specify the name of the specs files.
framework: 'jasmine',
specs: ['inksoftdata.js'],
jasmineNodeOpts: {
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 1440000
},
}
In testdata1.json file, all the data are stored as an array of objects. So to access the data from testdata1 variable you need to specify the array index like testdata1[0].firstName.

Get a local json file on NativeScript

How to get a local big json data?
I have tried this, but I had no success:
var sa = require("./shared/resources/sa.json");
var array = new observableArrayModule.ObservableArray(sa);
Use the file-system module to read the file and then parse it with JSON.parse():
var fs = require('file-system');
var documents = fs.knownFolders.currentApp();
var jsonFile = documents.getFile('shared/resources/sa.json');
var array;
var jsonData;
jsonFile.readText()
.then(function (content) {
try {
jsonData = JSON.parse(content);
array = new observableArrayModule.ObservableArray(jsonData);
} catch (err) {
throw new Error('Could not parse JSON file');
}
}, function (error) {
throw new Error('Could not read JSON file');
});
Here's a real life example of how I'm doing it in a NativeScript app to read a 75kb/250 000 characters big JSON file.
TypeScript:
import {knownFolders} from "tns-core-modules/file-system";
export class Something {
loadFile() {
let appFolder = knownFolders.currentApp();
let cfgFile = appFolder.getFile("config/config.json");
console.log(cfgFile.readTextSync());
}
}
As of TypeScript version 2.9.x and above (in NativeScript 5.x.x is using versions 3.1.1 and above) we can now use resovleJsonModule option for tsconfig.json. With this option, the JSON files can now be imported just as modules and the code is simpler to use, read and maintain.
For example, we can do:
import config from "./config.json";
console.log(config.count); // 42
console.log(config.env); // "debug"
All we need to do is to use TypeScript 2.9.x and above and enable the propety in tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
A sample project demonstrating the above can be found here
I just wanted to add one more thing, which might be even easier. You can simply write the content of your JSON file in a data.js file, or whatever name you would like to use, and export it as an array. Then you can just require the data.js module.

Get "file basename" in gulp-replacer-task

I'm manipulating a set of files and I am using gulp-replacer-task to replace the content of processed files with "strings" based on the basename or path of the file currently in the pipe-line.
How do i get at the file's properties currently in the pipe-line ?
gulp.task('svgbuild', function() {
return gulp.src('./src/*.svg')
.pipe(replace({
patterns: [
{
match: /STRING_TO_MATCH/g,
replacement: function() {
// how to get the basename of the "file" in the stream;
var str = 'file.basename'
// manipulate to get replacement string based on basename
var repl = str.toUpperCase()+'-inc'
return repl;
}
}
]
}))
});
Somewhat later than I hoped, but it appears I found a solution for the problem using gulp-tap. This is what my gulpfile.js looks like:
var gulp = require('gulp'),
path = require('path'),
replace = require('gulp-replace-task'),
tap = require('gulp-tap');
gulp.task('svgbuild', function () {
return gulp.src('*.txt')
.pipe(tap(function (file) {
return gulp.src(file.path)
.pipe(replace({
patterns: [
{
match: /foo/g,
replacement: function () {
var ext = path.extname(file.path),
base = path.basename(file.path, ext);
return base.toUpperCase() + '-inc'
}
}
]
}))
.pipe(gulp.dest('build'));
}));
});
I think you must look for the solution in Node.js. Maybe this helps: https://nodejs.org/api/path.html?

Convert Json into Xlsx File

I am trying to covert json data into Xlsx file and save it in a folder.
I have been trying to use icg-json-to-xlsx module but till now I have been unable to use it.
My code looks like this:
jsonXlsx = require('icg-json-to-xlsx');
filename = path.join('./files', "output.xlsx");
outputFile = jsonXlsx(filename, result) //result contains json data
console.log(outputFile);
but I got this error
outputFile = jsonXlsx(filename, result)
^
TypeError: Property 'jsonXlsx' of object # is not a function
Getting data from mongodb:
in routes:
router.get('/', function(req, res, next) {
fileController.getAll(function(err, result){
if(err){
res.send(500,err);
}
// res.json(result);
var data = result;
in controller:
FileController.prototype.getAll = function(callback){
File.find( {}, {_id: false, id: true, name: true, status: true}, function(err, file){
if(err) {
return callback(err);
} else {
if (!file) {
return callback('file not found');
}
}
callback(null, file);
}
)};
Try this
outputFile = jsonXlsx.writeFile(filename, result);
jsonXlsx is object, which contains methods like writeFile, writeBuffer, so you can't call jsonXlsx as function... or you need add reference to function like this
jsonXlsxWriteFile = require('icg-json-to-xlsx').writeFile;
outputFile = jsonXlsxWriteFile(filename, result)
Example
var jsonXlsx = require('icg-json-to-xlsx');
var path = require('path');
var filename = path.join('./files', "output.xlsx");
var result = [
{ id: '1', name: 'test', status: '123' },
{ id: '2', name: 'david', status: '323'},
{ id: '3', name: 'ram', status: '2323' }
];
var outputFile = jsonXlsx.writeFile(filename, JSON.stringify(result));
console.log(outputFile);
Update:
File
.find({ })
.select({
_id: false, id: true, name: true, status: true
})
.lean()
.exec(function(err, file) {
//
});
In your case, query returns MongooseDocuments, but jsonXlsx needs plain JavaScript objects, so that's why you should use lean()
You can try Alasql JavaScript SQL library. It includes a module to work with JSON and XLSX files (with support of js-xlsx.js library).
Install these two libraries into your project.
npm install alasql
npm install xlsx
Then call alasql function:
var alasql = require(alasql);
alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) \
FROM JSON("mydata.json")');
var cities = [{City:'London',Population:2500000},{City:"Paris",Population:2000000}];
alasql("SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?",[cities]);
See more examples in this demo file.
There are a lot of modules that can do it. But if you want to control the formatting of xlsx file, then I suggest you use this below code. Rows contain data in the form of JSON array.
var excel = require('node-excel-export');
var styles = {
headerDark: {
fill: {
fgColor: {
rgb: 'FF000000'
}
},
font: {
color: {
rgb: 'FFFFFFFF'
},
sz: 14,
bold: true,
underline: true
}
},
cellPink: {
fill: {
fgColor: {
rgb: 'FFFFCCFF'
}
}
},
cellGreen: {
fill: {
fgColor: {
rgb: 'FF00FF00'
}
}
}
};
var specification = {
"Col1": {
"displayName": 'Col1Name',
"headerStyle": styles.headerDark,
"width": 250
},
"Col2": {
"displayName": 'Col2Name',
"headerStyle": styles.headerDark,
"width": 215
},
"Col3": {
displayName: 'Col3Name',
headerStyle: styles.headerDark,
width: 150
}
}
var report = excel.buildExport(
[{
name: 'Report.xlsx',
specification: specification,
data: rows
}]
);