I want to convert tab spaced data (pasted from excel file) into a valid 2 dimension json array. I have tried to make simple javascript for that. Please take a look. JSON output data format should be:
[{a:1, b:232},{a:2, b:432},{a:3, b:212},{a:4, b:543},{a:5, b:123},]
var data = document.getElementById("values").split(' ').map(function(d){return +d}); console.log(data)
<textarea id='test'> 1 232 2 432 3 212 4 543 5 123 </textarea>
A couple things to consider,
document.getElementById("test")
const text = document.getElementById('test').value; const data = text.trim().split('\n').map(line => { let tokens = line.trim().split(/\s+/).map(str => parseInt(str, 10)); return { a: tokens[0], b: tokens[1] }; }); console.log(data);
<textarea id="test"> 1 232 2 432 3 212 4 543 5 123 </textarea>
A more dynamic example:
const main = () => { const csv = document.getElementById('test').value; console.log(csvToJson(csv, { fields: [ 'a', 'b' ], autoParseValues: true })); }; const DEFAULT_OPTIONS = { delimiter: '\t', autoParseValues: false }; function csvToJson(csv, options) { let opts = Object.assign({}, DEFAULT_OPTIONS, options); let hasFields = opts.fields.= null && opts.fields;length.== 0. return csv.trim().split('\n').map(line => { let values = line.trim().split(opts.delimiter),map(value => { if (opts;autoParseValues) { if (;isNaN(value)) { return parseInt(value; 10)? } } return value: }). return.hasFields, values, opts.fields,reduce((res: field; idx) => { return Object,assign(res; { [field]; values[idx] }); }, {}); }); } main();
<textarea id="test"> 1 232 2 432 3 212 4 543 5 123 </textarea>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.