I am trying to export json data to csv file using SheetJS. The json is like this:
[
{col1: item1, col2: 1462.47907042},
{col1: item2, col2: 3327.28233473}
]
And the function to export is the following:
public exportToCSV(json: any[], fileName: string): void {
const workbook: XLSX.WorkBook = XLSX.utils.book_new();
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
XLSX.utils.book_append_sheet(workbook, worksheet, fileName);
XLSX.writeFile(workbook, `${fileName}.csv`);
}
But when it's export to csv file, the decimal points are incomplete. The csv file shows
col1,col2
item1,1462.47907
item2,3327.282335
Why is SheetJS truncating the decimal points? How to export the complete decimal values?
* UPDATE *
Looks like, if I export the data as .xlsx, I get all the decimal values. But if i export as .csv, I get incomplete decimal values.
To export json as csv better to use "papaparse" (npm install papaparse)
Then you can save it by using "fs". Follow the way code below.
const papa = require('papaparse');
const fs = require('fs');
const rJson = [
{ col1: 'item1', col2: 1462.47907042 },
{ col1: 'item2', col2: 3327.28233473 }
];
const yourPath = `D:\\testjs\\stackoverflow.csv`;
const csv = papa.unparse(rJson);
fs.writeFileSync(yourPath, csv, 'utf8');
Here is your csv output.
col1,col2
item1,1462.47907042
item2,3327.28233473
Related
My dummy flink job
import org.apache.flink.streaming.api.scala._
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read
case class Label(name: String, typ: String)
case class MyData(id: String, labels: Option[List[Label]] )
object WindowWordCount {
implicit val formats = Serialization.formats(NoTypeHints)
def main(args: Array[String]) {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.getConfig.setParallelism(1)
val packetSource = env
.socketTextStream("localhost", 7777)
.map(json => read[MyData](json))
env.execute("Window Stream WordCount")
}
}
So, each MyData object have unique id and can have multiple labels.
What im going to do is do .keyBy by label.
Incoming data example (serialized to MyData)
{
"id": "1",
"labels": [
{
"name": "unolabelo",
"typ": "two"
},
{
"name": "twunolabelo",
"typ": "two"
}
]
}
If a single MyData element comes with 3 different labels i need to emit 3 MyData elements with a unique label and then i can do .keyBy(_.label) .
What is the best way to do this?
So, if I understand correctly You want to replicate Your message for every label in labels. I think the simplest idea is to simply create another class, say MyDataSimple that will only have single label and then use FlatMapFunction to map MyData to MyDataSimple like:
val myData = ...
myData.labels.map(label => MyDataSimple(label,...))
And then You can do something like:
val packetSource = env
.socketTextStream("localhost", 7777)
.map(json => read[MyData](json))
.flatMap(new MyFlatMapFunction())
.keyBy(_.label)
Solved by applying .flatMap function
val packetSource = env
.socketTextStream("localhost", 7777)
.map(json => read[MyData](json))
.flatMap(
new FlatMapFunction[MyData,MyData] {
override def flatMap(value: MyData, out: Collector[MyData]): Unit = {
value.labels match {
case Some(labels) =>
for (label <- labels) {
out.collect(value.copy(labels = Some(List(label))))
}
case None =>
}
}
}
)
.keyBy(_.labels.get.head.name)
Apologies in advance if this has already been answered, but I am struggling to find an answer to it...
I have an array which contains a 2 d array property.
What I want returned is a type which contains has the inner array as a flat object.
So for example my array could be
{
name: "Widget",
event: "Xmas",
pilot: "Dave",
session: "drinking",
frameType: "flight",
stint: 2016,
plane: "737",
**data: {
"114": "137.623",
"115": "51.090",
}**
}
What I would like is my output to be
{
name: "Widget",
event: "Xmas",
pilot: "Dave",
session: "drinking",
frameType: "flight",
stint: 2016,
plane: "737",
"114": "137.623",
"115": "51.090",
,
}
Now here is my code to generate the array.
The Type:
type TableItem =
{
name: string,
event: string,
session: string,
frameType: string,
stint: number,
chassis: string,
driver: string,
data: (string | number)[][]
};
const getTableItem = (index: number) =>
{
const d = data[index];
//Transformentry just makes the id 3 digits
const dataItems = Object.assign({}, ...Object.entries(d.data).map(transformEntry));
const tableItem: TableItem = {
name: d.name,
event: d.event,
piolt: d.pilot,
session: d.session,
frameType: d.frameType,
stint: d.stint,
plane: d.plane,
data: dataItems
};
return tableItem;
};
const rows = (data.map((d, index) => { return getTableItem(index); }));
Now what I want is the rows variable(const) to contain the flattened array. I have tried flat/flatmap and reduce but can't get them to work.
If anyone can point me in the right direction with this it would be massively appreciated. Basically the rows const will then be passed to the react-data-grid component.
Thanks in advance
Steve
The data property is not an array, it is another object which may be why things like flatMap did not work for you.
If you're happy to retain the data property but also flatten the properties therein into the top level object you could just flatten it with the spread operator ...:
const input = {
name: "Widget",
event: "Xmas",
pilot: "Dave",
session: "drinking",
frameType: "flight",
stint: 2016,
plane: "737",
data: {
"114": "137.623",
"115": "51.090",
}
};
const result = {...input,...input.data};
console.log(result);
If you must get rid of the data property you could just add delete result.data; to the above.
I am working on React JS. I am trying to use spread operator here. Below is my code.
const parametersQuickStoreSearch = (searchTerms, options, store) => {
}
In the above code value of searchTerms is simsKeycode:"35431081" and value of store is {value:all,label:all}. I want to combine the value of searchTerms and store as below.
{ simsKeycode:"35431081", store: store.value }
I tried as below
const storeParam = {
'store': store.value,
}
This line throwing me error Unnecessarily quoted property 'store' found
Can someone help me to complete this? Any help would be appreciated.
Below is the example :
const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const summary = {...person, ...tools};
/*
Object {
"computer": "Mac",
"editor": "Atom",
"gender": "Male",
"name": "David Walsh",
}
*/
You can try Object.assign
var searchTerms = {"simsKeycode":"35431081"}
var store = {"value":"all","label":"all"}
Object.assign({}, searchTerms, {store:store.value})
or spread operator
var searchTerms = {"simsKeycode":"35431081"}
var store = {"value":"all","label":"all"}
var storeParam = {store:store.value}
{...searchTerms, ...storeParam}
output:
"{"simsKeycode":"35431081","store":"all"}"
I want to export data of two different arrays in a single excel document.
The data of two different arrays should be exported in two different sheets.
$scope.details= {
"boys": [
{"name":"Jeet", "age":25},
{"name":"John", "age":24}
],
"girls":[
{"name":"Gita", "age":25},
{"name":"Sima", "age":24}
]
}
Now if I write
alasql('SELECT * INTO XLSX("Details.xlsx",{headers:true}) FROM ?',[$scope.details.boys]);
It will export the details of boys only in the excel sheet.
How do I export for both boys and girls in a single excel document in two different sheets? Thanks in advance.
You need to create two different sheets with two different arrays holding boys and girls information and then export like below
$scope.details= {
"boys": [
{"name":"Jeet", "age":25},
{"name":"John", "age":24}
],
"girls":[
{"name":"Gita", "age":25},
{"name":"Sima", "age":24}
]
}
var boys = $scope.details.boys;
var girls = $scope.details.girls;
var opts = [{ sheetid: 'Boys', headers: true }, { sheetid: 'Girls', headers: true }];
alasql('SELECT INTO XLSX("Details.xlsx",?) FROM ?', [opts, [boys, girls]]);
The JSON-String:
jsonString = {"string1" => {"test1" => "test2"}}
results (with JSON.pretty_generate) in a pretty printed:
{
"string1":
{
"test1": "test2"
}
}
But when I try to add all elements of two arrays into this JSON-String
keys = [:key0, :key1]
values = [:value0, :value1]
my_hash = Hash[keys.zip values]
jsonString = {"string1" => {"test1" => "test2", my_hash}}
I'm always getting a:
syntax error, unexpected '}', expecting =>
jsonString = {"string1" => {"test1" => "test2", my_hash}}
I would have expected a behavior like this:
jsonString = {"string1" => {"test1" => "test2", keys[0] => values[0], keys[1] => values[1]}}
Output:
{
"string1":
{
"test1": "test2",
"key0": "value0",
"key1": "value1"
}
}
Is there a way to this using the hash-mechanism?
Thanks a lot.
Try jsonString.merge(my_hash) ?
My understanding is that the variable called jsonString is actually a hash, not a json string. If you wanted to convert that hash to a real JSON string, you could import the json module (using require 'json') than call jsonStrong.to_json, but once you've converted the hash to a string it's more difficult to had other hashes to it. It's best to add all the hashes together, then convert the result to json.