Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  114] [ 4]  / answers: 1 / hits: 25228  / 8 Years ago, sun, march 20, 2016, 12:00:00

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


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}]


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)
});
}]);

More From » json

 Answers
4

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) Headings are the first nested array in cells.



var headings = cells.shift();


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) Stringify the returned object.



var json = JSON.stringify(obj);


OUTPUT



[
{
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
}
]


DEMO


[#62868] Thursday, March 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseb

Total Points: 252
Total Questions: 96
Total Answers: 106

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
analiseb questions
;