-2

I'm wondering if it possible in JS to read a local broken JSON file? I dont have any control over the local json file that is created. Im trying to figure out If i can read all lines before the extra comma.

import Users from './users.json'

[
  {
    "name": "Rob"
  },
  {
    "name": "Chris"
  },
  {
    "name": "Daniel"
  },
]
Graeme Paul
  • 1,143
  • 1
  • 16
  • 30
  • Are you open to writing your own JSON parser? – zero298 Jun 25 '18 at 15:56
  • 2
    stringify the data, remove the last comma then parse JSON – Boo Jun 25 '18 at 15:57
  • 1
    Is the JSON always going to be structured like that (with only siblings)? If so, then @Boo's suggestion will work. If you don't know, then it's going to have to be flexible. In that case, maybe this library will help: https://github.com/RyanMarcus/dirty-json – mccambridge Jun 25 '18 at 15:59
  • You can use the [JSON5 parser](https://stackoverflow.com/a/25469529) – Heretic Monkey Jun 25 '18 at 16:01
  • JSON5 works if you have the json object inline, otherwise it gets stuck on importing the JSON file. By either import Users from './users.json' or const users = require('./users.json) – Graeme Paul Jun 26 '18 at 08:30

2 Answers2

2

You would need to add some regular expression replacing logic to remove illegal characters. This is just a basic example.

var json = `[
  {
    "name": "Rob"
  },
  {
    "name": "Chris"
  },
  {
    "name": "Daniel"
  },
]`

var parsedJson = JSON.parse(json.replace(/\},\s*\]/g, '}]'))

console.log(parsedJson)
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

You have to write some kind of JSON parser where you have to read character by character to parse the file;

var readable = fs.createReadStream("jsonfile.json", {
  encoding: 'utf8',
  fd: null,
});

readable.on('readable', function() {
  var chunk;
  while (null !== (chunk = readable.read(1))) {
    //chunk is one character
    if(chunk == "["){ //JSON array is started }
    if(chunk == "{"){ //Handle JSON object started}

    //In between you can parse each character until you get a `:` character to 
    //identify the key and from there up to a comma it is value. (** Considering the simple JSON file example you provided**)

    if(chunk == "}"){ //Handle JSON object end}
    if(chunk == "]"){ //Handle JSON array end}
  }
});

But I suggest you to go some kind of library for this. Else it will itself a separate project. Anyway for you example JSON type, you can write one yourself as the format is quite simple and you know what can be the issue (extra comma).

Generalize solution will be much more difficult.

KOUSIK MANDAL
  • 2,002
  • 1
  • 21
  • 46