如何在javascript中将文本文件转换为json [英] how to convert text file to json in javascript
本文介绍了如何在javascript中将文本文件转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面的文本文件
I have a text file like the one below
id nm lat lon countryCode
819827 Razvilka 55.591667 37.740833 RU
524901 Moscow 55.752220 37.615555 RU
1271881 Firozpur 27.799999 76.949997 IN
我需要像下面的格式一样转换为json
i need to to convert to json like the format below
[{"id":819827,"nm":"Razvilka","lat":55.591667,"lon":37.740833,"countryCode":"RU"},
{"id":524901,"nm":"Moscow","lat":55.752220,"lon":37.615555,"countryCode":"RU"},
{"id":1271881,"nm":"Firozpur","lat":27.799999,"lon":76.949997,"countryCode":"IN"}]
用于javascript应用程序.
for a javascript application.
myapp.controller('TCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('list.txt').success(function(data) {
$scope.todos = JSON.parse(data);
//console.log(data)
});
}]);
推荐答案
1)通过分割回车符(行)上的字符串,然后使用map
返回基于行的新数组来获取单元格数组在空格上分开.
1) Get an array of cells by splitting the string on the carriage return (rows), then using map
to return an new array based on the row split on the spaces.
var cells = str.split('\n').map(function (el) { return el.split(/\s+/); });
2)标题是cells
中的第一个嵌套数组.
2) Headings are the first nested array in cells
.
var headings = cells.shift();
3)map
在单元格上构建并根据值返回新对象.
3) map
over the cells building and returning a new object based on the values.
var obj = cells.map(function (el) {
var obj = {};
for (var i = 0, l = el.length; i < l; i++) {
obj[headings[i]] = isNaN(Number(el[i])) ? el[i] : +el[i];
}
return obj;
});
4)字符串化返回的对象.
4) Stringify the returned object.
var json = JSON.stringify(obj);
输出
[
{
"id": 819827,
"nm": "Razvilka",
"lat": 55.591667,
"lon": 37.740833,
"countryCode": "RU"
},
{
"id": 524901,
"nm": "Moscow",
"lat": 55.75222,
"lon": 37.615555,
"countryCode": "RU"
},
{
"id": 1271881,
"nm": "Firozpur",
"lat": 27.799999,
"lon": 76.949997,
"countryCode": "IN"
}
]
这篇关于如何在javascript中将文本文件转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文