neuroo / json-ast

A tolerant JSON parser for Node
https://www.npmjs.com/package/json-ast
MIT License
20 stars 7 forks source link

AST Printer with comments? #6

Open mohsen1 opened 5 years ago

mohsen1 commented 5 years ago

I would like to use this package to pars and then pretty print JSON with comments. How can I do that? Using AST.JsonDocument.toJSON(ast) and similar methods does not sustain comments

neuroo commented 5 years ago

toJSON will return the actual JSON object that can be passed to JSON.stringify. If you want to print comments, you need to implement a Visitor that will output them, e.g.:

class MyVisitor extends Visitor {
  constructor() { super(); };

  // pretty printer for all nodes and then for comments:
  comment(commentNode) {
    console.log('[COMMENT]', commentNode.value);
  };
};
mohsen1 commented 5 years ago

I would like to maintain comment locations as much as possible. I will try using the visitor to print. Do you have an example of printer written with the visitor?

char0n commented 4 years ago

@mohsen1 here is an example of CommentVisitor doing printing:

'use strict';

const { parse, Visitor, AST } = require('./index');

const json = `
// before-everything - 1
{"a": "b"}
// after-everything - 1
`;

class CommentVisitor extends Visitor {
  constructor() {
    super();
  }

  comment(commentNode) {
    console.log(`Comment intercepted: ${commentNode.value}`);
    console.log(`Position: ${commentNode.position.human}`);
    console.log('---------------------')
  }
}

const ast = parse(json, {verbose: true, junker: true});
const visitor = new CommentVisitor();
ast.accept(visitor);