Giter Site home page Giter Site logo

json-asty's Introduction

JSON-ASTy

Lossless JSON-to-AST Parser and AST-to-JSON Generator

github (author stars) github (author followers)
npm (project release) npm (project downloads)

About

JSON-ASTy is a JavaScript library providing a lossless JavaScript Object Notation (JSON) to Abstract Syntax Tree (AST) parser and a corresponding AST to JSON generator. It is intended for cases where one has to read JSON into an AST, manipulate the AST and generate JSON from the AST again while fully preserving the formatting of the original JSON. The AST is based on ASTy-ASTq, and hence can powerfully queried with ASTq, and manipulated with ASTy.

Installation

$ npm install json-asty

Usage

const JsonAsty = require("json-asty")

/*  the JSON input  */
let json = `{
    "foo": {
        "bar": true,
        "baz": 42.0,
        "quux": [ "test1\\"test2", "test3", 7, true ]
    }
}`
console.log(`JSON (old):\n${json}`)

/*  parse JSON into AST  */
let ast = JsonAsty.parse(json)
console.log(`AST Dump (all):\n${JsonAsty.dump(ast, { colors: true })}`)

/*  the AST query  */
let query = `
    .// member [
        ..// member [
            / string [ pos() == 1 && @value == "foo" ]
        ]
        &&
        / string [ pos() == 1 && @value == "baz" ]
    ]
        / * [ pos() == 2 ]
`
console.log(`AST Query:\n${query}`)

/*  query AST node  */
let nodes = ast.query(query)
let node = nodes[0]
console.log(`AST Dump (sub, old):\n${node.dump()}`)

/*  manipulate AST node  */
let nodeNew = node.create("string").set({ value: "TEST" })
node.parent().del(node).add(nodeNew)
console.log(`AST Dump (sub, new):\n${node.dump()}`)

/*  unparse AST into JSON  */
let jsonNew = JsonAsty.unparse(ast)
console.log(`JSON (new):\n${jsonNew}`)

Output:

JSON (old):
{
    "foo": {
        "bar": true,
        "baz": 42.0,
        "quux": [ "test1\"test2", "test3", 7, true ]
    }
}
AST Dump (all):
object (prolog: "{\n    ", epilog: "}") [1,1]
└── member [2,5]
    ├── string (body: "\"foo\"", value: "foo", epilog: ": ") [2,5]
    └── object (prolog: "{\n        ", epilog: "}\n") [2,12]
        ├── member (epilog: ",\n        ") [3,9]
        │   ├── string (body: "\"bar\"", value: "bar", epilog: ": ") [3,9]
        │   └── boolean (body: "true", value: true) [3,16]
        ├── member (epilog: ",\n        ") [4,9]
        │   ├── string (body: "\"baz\"", value: "baz", epilog: ": ") [4,9]
        │   └── number (body: "42.0", value: 42) [4,16]
        └── member [5,9]
            ├── string (body: "\"quux\"", value: "quux", epilog: ": ") [5,9]
            └── array (prolog: "[ ", epilog: " ]\n    ") [5,17]
                ├── string (body: "\"test1\\\"test2\"", value: "test1\"test2", epilog: ", ") [5,19]
                ├── string (body: "\"test3\"", value: "test3", epilog: ", ") [5,35]
                ├── number (body: "7", value: 7, epilog: ", ") [5,44]
                └── boolean (body: "true", value: true) [5,47]

AST Query:

    .// member [
        ..// member [
            / string [ pos() == 1 && @value == "foo" ]
        ]
        &&
        / string [ pos() == 1 && @value == "baz" ]
    ]
        / * [ pos() == 2 ]

AST Dump (sub, old):
number (body: "42.0", value: 42) [4,16]

AST Dump (sub, new):
number (body: "42.0", value: 42) [4,16]

JSON (new):
{
    "foo": {
        "bar": true,
        "baz": "TEST",
        "quux": [ "test1\"test2", "test3", 7, true ]
    }
}

License

Copyright © 2018-2024 Dr. Ralf S. Engelschall (http://engelschall.com/)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

json-asty's People

Contributors

rse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

davidarchibald

json-asty's Issues

Cannot find module 'asty' when imported in create-react-app project

Excellent library! I'd like to use it in my project based on create-react-app, but I'm getting the Cannot find module 'asty' message.

Steps to reproduce:

  1. npx create-react-app json-asty-cra
  2. In json-asty-cra directory, edit package.json to add the "json-asty": "1.0.5" dependency.
  3. In src/App.js, add import JsonAsty from "json-asty";
  4. Start development server: npm start.
  5. Open http://localhost:3000. You will get the Cannot find module 'asty' message.
  6. After npm build, the same error appears when running the production build.

Any ideas how to resolve this? I'd really like to use json-asty, it would make things so much easier in my code.

List of Objects Doesn't Add Closing Bracket to Objects When Calling JsonAsty.unparse()

I am running into an issue when using this with a list of objects. For example, I have changed the sample JSON object from the repo/npm page to this (changed foo to a list of objects):

{ "foo": [ { "bar": true, "baz": 42.0, "quux": [ "test1\\"test2", "test3", 7, true ] }, { "bar": true, "baz": 42.0, "quux": [ "test1\\"test2", "test3", 7, true ] } ] }

Everything works correct in terms of reading the JSON and creating the AST, but when unparsing the AST back to JSON, the list of objects looks like this:

{ "foo": [ { "bar": true, "baz": 42.0, "quux": [ "test1\\"test2", "test3", 7, true ] , { "bar": true, "baz": 42.0, "quux": [ "test1\\"test2", "test3", 7, true ] } ] }

I think the reason for this is when creating the AST, the epilog for the first object is being set to "," and it is ignoring the closing bracket when unparsing, whereas the epilog for the last object in the list, the epilog is being set to "}" and being unparsed correctly. Is this a bug or am I using the library wrong? Thanks in advanced!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.