Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read json file ignoring custom comments

How can i read this file 'file.json':

# Comment01
# Comment02
{
   "name": "MyName"
}

and retrieve the json without comments?

I'm using this code:

var fs = require('fs');
var obj;
fs.readFile('./file.json', 'utf8', function (err, data) { 
  if (err) throw err;
  obj = JSON.parse(data);
});

it returns this error:

SyntaxError: Unexpected token # in JSON at position 0

Have npm some package to solve this question?

like image 796
Hemã Vidal Avatar asked Nov 18 '16 20:11

Hemã Vidal


People also ask

Why JSON not allow comments?

So while JSON is often closely associated with JavaScript (even though it's used by most other languages as well), it does not support the same commenting features as JavaScript as it's a data-only specification. Comments were removed from the JSON specification because they were being used as parsing directives, which ...

Do JSON files support comments?

If you're having trouble adding comments to your JSON file, there's a good reason: JSON doesn't support comments.

How do I comment out a line in JSON file?

Open the JSON file in your text editor and add comments the same way you would in Python (using # and not docstrings) or the same way you would in JavaScript (using // and not multi-line comments using /** */ ).

Is JSON parse asynchronous?

The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).


2 Answers

The perfect package for this problem is https://www.npmjs.com/package/hjson

hjsonText input:


{
  # hash style comments
  # (because it's just one character)

  // line style comments
  // (because it's like C/JavaScript/...)

  /* block style comments because
     it allows you to comment out a block */

  # Everything you do in comments,
  # stays in comments ;-}
}

Usage:

var Hjson = require('hjson');

var obj = Hjson.parse(hjsonText);
var text2 = Hjson.stringify(obj);
like image 148
Hemã Vidal Avatar answered Sep 26 '22 20:09

Hemã Vidal


You can use your own RegExp pretty easily to match the comments beginning with a #

const matchHashComment = new RegExp(/(#.*)/, 'gi');
const fs = require('fs');

fs.readFile('./file.json', (err, data) => {
    // replaces all hash comments & trim the resulting string
    let json = data.toString('utf8').replace(matchHashComment, '').trim();  
    json = JSON.parse(json);
    console.log(json);
});
like image 21
peteb Avatar answered Sep 25 '22 20:09

peteb