parsing json data without a comma separator

Viewed 13106

My JSON is like below

{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}
{"_id":1270260,"name":"State of Haryāna","country":"IN","coord":{"lon":76,"lat":29}}
{"_id":708546,"name":"Holubynka","country":"UA","coord":{"lon":33.900002,"lat":44.599998}}

It is a JSON without comma separation, how to read this file? I tried to parse the JSON and add commas in between, but couldn't do that either.

myapp.controller('Ctrl', ['$scope', '$http', function($scope, $http) {
  $http.get('todos.json').success(function(data) {
    var nuarr = data.toString().split("\n");
    for(i in nuarr) {
      myjson.push(i+",");
    }
  });
}]);
9 Answers

As stupid as it may seem, we got tired of using commas and quotes with JSON, along with not having comments or multiline strings.

Knowing that Douglas Crockford and his disciples would cry 'Blasphemy', we proceeded to write a specification, parser, and formatter for our own Relaxed Json syntax.

The fact is you don't really need commas, and quotes are only needed in a few exceptional cases. And you don't need newlines either.

With Relaxed Json, to make your example work, you would just put '[' and ']' around what you already have and call

val realJson = parser.stringToJson(...)

  • But you don't need newlines between the array values.

  • And you can also remove all the commas in-between your key-values.

  • And you don't need quotes around your keys.

So you could do this:

[ 
  { _id:707860 name:Hurzuf country:UA
    coord:{lon:34.283333 lat:44.549999}
  }
  { _id:519188 name:Novinki country:RU 
    coord:{lon:37.666668 lat:55.683334}
  }
]

Link To Specification: http://www.relaxedjson.org

Link To NPM https://www.npmjs.com/package/really-relaxed-json

Paste the example here to see how easy it is to parse: http://www.relaxedjson.org/docs/converter.html

Update 2022

@milkandtang answer put me on the right path but JSON.parse() gave me trouble and returned errors even after splitting the lines. It keeps complaining about lines being empty or malformated.

This is what works for me with New-Line Delimited JSON

var ndjson = data;//must be a string

//declare variable that will be array of json
var json = []; 

//split
ndjson.split('\n').map(function (record) {

//regex to format each array to a json object
var array = JSON.parse(`[${record.replace(/\}\n\{/g, '},{')}]`);

//push to json array
json.push(array);

})

//pheeew...
console.log(json);
Related