Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Coverting into JSON Array

This is my text file:

2|BATH BENCH|19.00
20312100000|ORANGE BELL|1.42
04525514840|BOILER ONION|1.78
20422500000|AVOCADO|0.98

My job is the extract the barcode which is 2,20312100000, 04525514840, 2042250000 and convert into a json array which should look like: ["2","20312100000","04525514840","20422500000"]

The code I have is this:

var FilePath = process.argv[2];
var allUpcs = [];

const fs = require('fs');
const readline = require('readline');

const file = readline.createInterface({
input: fs.createReadStream(FilePath),
output: process.stdout,
terminal: false
});

file.on('line', (line) => {
allUpcs.push(line.split('|')[0]);
});

file.on('close', function() {
// console.log(allUpcs.map(Number));
// console.log(JSON.stringify(allUpcs));
console.log(JSON.stringify(allUpcs));
});

I am getting output as this:

[“2”,“20312100000",“04525514840”,“20422500000"]

I need to convert it into json array, can anyone please help thank you.

question from:https://stackoverflow.com/questions/65893885/coverting-into-json-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only need to do JSON.stringify twice, you can get the format you want.

Hava a good day :)

const data =["2","20312100000","04525514840","20422500000"];
console.log('object',data);
console.log('string',JSON.stringify(data));
console.log('string',JSON.stringify(JSON.stringify(data)));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...