grails excel-import plugin csv issue - csv

I am using grails Excel-import plugin to import Excel and csv files.For excel files it works fine.But I am having a tough time to make it work for csv. I refferd the code in the following stack overflow Question
Import CSV with import-excel plugin in grails
I tried to bind the csv file with my csvImport class by using readFromFile and readFromURL method(these i found in the plugin'test directory in bootstrap.groovy).this is the code for my csvImport file
import org.grails.plugins.excelimport.*
class csvImport extends AbstractCsvImporter {
static Map configMap = [
startRow: 1,
columnMap: [
0: 'title',
1: 'author',
2: 'numSold'
]
]
def readCsv(File fileName){
read(fileName)
}
List<Map> getList(CONFIG_COLUMN_MAP) {
getData(CONFIG_COLUMN_MAP)
}
List<Map> createListFromCSV(CONFIG_COLUMN_MAP) {
def csvList = this.getList(CONFIG_COLUMN_MAP)
log.info("<<<csvList>>>>"+csvList)
}
and in controller i am trying to call it like this
def csvImportIntance=new csvImport()
csvImportIntance.readCsv(new File("D:\\Folder\\testCSV.csv"))
def bookParamsList= csvImportIntance.createListFromCSV(CONFIG_COLUMN_MAP)
the file is ms-excel csv file.
Thanks in advance for any help.

First of all you class name should start with a capital letter.

Related

Read JSON file from file in Angular

I have a JSON file config.json saved in the src/app/config directory.
[
"caseSensitive",
"matchKeywords",
"items"
]
I have to read the file and get the content of the JSON file without parsing it.
After searching for it, I got two ways
Add "resolveJsonModule": true to the tsconfig.json file
Declara a typing module declare module "*.json" {}
and importing JSON as
import * as data from './app/config/config.json';
export class SchemaService {
constructor() { }
getConfig() {
console.log('bool: ', data); // Output in screenshot
console.log('type: ', typeof BooleanData); // object
console.log('parsed: ', JSON.stringify(BooleanData));
}
}
But both the ways are giving the parsed output as
The JSON.stringify(BooleanData) statement is not giving the actual JSON file, instead, the array items are changed to key-value where the index is represented as key
{
"0":"caseSensitive",
"1":"matchKeywords",
"2":"items"
}
How can I read the raw JSON (without parsing) in Angular, or at least convert an object into JSON?
You can use a quickfix provide by #amer-yousuf But it will also let you import any .js file into your codebase as well. I wont prefer that. Here is an alternative approach
Define your config.json.ts (notice it ends with .ts and not .json) something like below
export const CONFIG = { // your JSON is assigned to CONFIG variable
"say": "hello world"
}
In your other .ts file where you want to use, use something like following code
import { CONFIG } from './config.json';
// ...
console.log(CONFIG.say);
// ...
Benefit of this method:
You can still use tslint/eslint on config.json.ts
Most editors will auto-complete for you
In Angular, to access the JSON as an object, you need to add the following two options to the tsconfig.json file:
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
Then you can import it within your service like the following:
import data from './app/config/config.json';
To access JSON as Module in Angular you should add these two lines into tsconfig.json file
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
Then you can import it anywhere you want within the app
import * as Characters from './configs/characters.json';
Finaly access the object from module
export class CharactersComponent {
public characters: CharacterModel[] = (Characters as any).default;
}

properly import default export from JSON module

I have a JSON translation file "./countries/es.json" in my Angular application that I want to import and loop through.
{
...
"Solomon Islands": "Islas Salomón",
"South Sudan": "Sudán del Sur",
...
}
I have "resolveJsonModule": true, in my tsconfig.json file, so in general import goes well.
import * as countries from './countries/es.json';
and if I access the object say countries['Solomon Islands'] I get 'Islas Salomón' that is correct.
However if want to enumerate all countries:
const countries_keys = Object.keys(countries);
countries_keys is an array with one value 'default'. In order to obtain the country list I need to do:
const countries_keys = Object.keys(countries['default']);
My question - is there a way to do the import cleanly so I get the object exactly as in JSON file?
If I had the source file like:
{
countries: {
...
"Solomon Islands": "Islas Salomón",
"South Sudan": "Sudán del Sur",
...
}
}
I could simply do:
import { countries } from './countries/es.json';
but is there a clean way to import my original file as equivalent JSON object without the additional 'default' property.
You need add allowSyntheticDefaultImports in your tsconfig.json.
tsconfig.json
{
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true
}
TS
import countries from './countries/es.json';
import is not a good idea here later on if you want to move your file to some server you will need to rewrite the whole logic i would suggest to use httpclient get call here.So move you file to assets folder and then
constructor(private http:HttpClient){
this.http.get('assets/yourfilepath').subscribe(data=>{
const countries_keys = Object.keys(data['countries']);
console.log(data['countries'])//data is your json object here
})
}
What worked form me was:
import countries from './countries/es.json';
This is the "default import"

How to find and replace data from one JSON file to another using Python?

JSON file contains below data and structure is same across all files, but data under profile will be changing quite frequently.
So, am trying for Python script which will copy and replace entire data under "Profile" node to another JSON files (As Config data is static as each machine has diff static values).
Algo:
Pharse JSON file
Read and extract Profile data
Pharse and replace Entire Profile data to another JSON file
{
"config":
[
{
"Name":"FW",
"MLC":"anotoly",
"Frame":"True",
"ImageUpload":"False"
}
],
"Profile":
[
{
"Title":"CLI",
"File":"",
"Profile":"H",
"App":"AI.exe",
"Location":"\\common\\Isolation",
"sensitivity":20
}
]
}
import json,os,sys
def testDataTransform():
source = 'C:/Users/WS/Downloads/Profile.json'
Destination = 'D:/OL/SV/4.json'
datastore= None
with open(source, 'r') as content_file:
content = content_file.read()
datastore = json.load(content)
This code is not working, any help would be great. Thanks.

Unable to print complete JSON using console.log

I am trying to import JSON file into Sample variable but only first few characters are displayed from Sample variable.
The sample.json is 20,00,000 characters, When i print Sample variable on Console only first 3,756 characters are printed.Is there any limitations on the characters that can be printed through console.log?
Complete data persists in Sample variable, I verified it by searching for strings that occur at the end of sample.json file
var Sample = require('./sample.json');
export default class proj extends Component {
constructor(props) {
super(props);
this.state = {
locations: [],
};
}
loadOnEvent() {
console.log(Sample);
//this.state={ locations : Sample };
}
}
Is there any other way to print data in Sample variable.
You have to convert json to string using JSON.stringify before logging.
/* ... */
loadOnEvent() {
console.log(JSON.stringify(Sample));
//this.state={ locations : Sample };
}
/* ... */
Try to use another way to load. Use fetch if file is remote or use fs if file is local.
If it is memory problem supposed by #Shota consider to use server side processing requests to json file. It is good solution to setup microservice which load json file at startup and handle requests to data struct parsed from json file.
Answer for webpack use case:
Configure webpack to use file-loader or copy-webpack-plugin for specifically this file because it enough big. Consider to load it in parallel with webpack bundle. If your application have big parts which need not each case they must be moved to separated bundles.

Angular 2 - how to fill a local variable with JSON data from an external file

The Angular 2 tutorials I have read place variables directly in the app.component.ts file. For example var BAR below, which pulls data though the {Foo} interface.
import {Component} from 'angular2/core';
import {Foo} from './foo';
#Component({
etc.
});
export class AppComponent {
bar = BAR;
}
var BAR: Foo[] = [
{ 'id': 1 },
{ 'id': 2 }
];
However, I have the data for BAR in a local JSON file. I don't believe {HTTP_PROVIDER} is necessary. How would I go about getting the JSON data from the external file?
Create a file with this content
export const BAR= [
{ 'id': 1 },
{ 'id': 2 }
];
save it as BarConfig.ts or some like
later use it as follows
import { BAR } from './BarConfig';
let bar= BAR;
or even better, use BAR directly where you needed
HTTP_PROVIDER is needed if you want to load a file using http.
Here is an example of how to load a local json file over http:
this.result = {friends:[]};
this.http.get('./friends.json').map((res: Response) => res.json()).subscribe(res => this.result = res);
More details here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
Juste put your .json file in your static folder (/assets if you are using the angular cli) and it should work.
Best option is to create json file and store json details inside file and call that file using like below.
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
return this.http.get('<json file path inside assets folder>.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.
You can use the Http provider in angular2
Make sure you place your local json file in the www folder.
getLocalFile(){
return this.http.get('./localFileName.json').
map(res => res.json());
}
This will return you the local JSON file.