Git Product home page Git Product logo

babel-plugin-object-to-json-parse's Introduction

babel-plugin-object-to-json-parse ๐Ÿš€

release License: MIT npm version

This repository is inspired by this article

As long as the JSON string is only evaluated once, the JSON.parse approach is much faster compared to the JavaScript object literal, especially for cold loads.

Object to JSON.parse

This plugin converts from object literal to JSON.parse

// before
const data = { foo: 42, bar: 1337 };

// after
const data = JSON.parse('{"foo":42,"bar":1337}');

How to use

Install

$ npm install babel-plugin-object-to-json-parse -D
or
$ yarn add babel-plugin-object-to-json-parse -D

setup .babelrc

{
  "plugins": ["object-to-json-parse"]
}

Options

minJSONStringSize (number, defaults to 1024)

The minJSONStringSize option will prevent the plugin from replacing an expression if the length of the JSON string given to JSON.parse is smaller than minJSONStringSize. For example, the following ensures all replacements have a string size of at least 1kb.

{
  "plugins": [
    ["object-to-json-parse", {
      "minJSONStringSize": 1024
    }]
  ]
}

Caution!!

this plugin may not be production ready

I just made this plugin for my understanding about AST and babel plugin.

this plugin doesn't support partially JSON expression

I decided not to support partially JSON expression like below.

Partially JSON expressions such as [notValid, {isValid:true}] ensuring {isValid:true} is transformed.

const data = { bar: invalid_object, foo: 'foo' }
โ†“
const data = { bar: invalid_object, JSON.parse('{"foo": "foo"}')}

This is because I think most large objects are not partially JSON expressions. JSON.parse() is much faster in the case that object is 10 kB or larger. Converting small object to JSON.parse expression is not meaningful.

this plugin produces output that only works in modern environments (e.g. Node.js v10+)

I don't care about some backwards compatibilities like this issue.

Development

Any contributions are welcomed from everyone!!

Setup

$ git clone [email protected]:nissy-dev/babel-plugin-object-to-json-parse.git
$ cd babel-plugin-object-to-json-parse
$ yarn install

Tips

// build
$ yarn build

// test
$ yarn test

babel-plugin-object-to-json-parse's People

Contributors

adrienz avatar dependabot[bot] avatar github-actions[bot] avatar nissy-dev avatar uhyo 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

babel-plugin-object-to-json-parse's Issues

Support partially JSON expression

At present, I decided not to support partially JSON expression like below in #27.

Partially JSON expressions such as [notValid, {isValid:true}] ensuring {isValid:true} is transformed.

const data = { bar: invalid_object, foo: 'foo' }
โ†“
const data = { bar: invalid_object, JSON.parse('{"foo": "foo"}')}

Does anyone need this feature?
If you need this feature, please comment on this issue with your detail ๐Ÿ™‡.

Number-keyed properties

Currently, this plugin cannot correctly convert number-keyed properties.

before

const obj = {
  123: "123",
  45: 45
};

console.log(obj[123]); // => "123"

after

const obj = JSON.parse('{"undefined":45}');
console.log(obj[123]); // => undefined

Escaping only the 1st occurence

I stumbled across a JSON.parse suddenly throwing and it seems that some \n are not properly escaped.

Reading the source code, it seems that because the RegExp is not using the global flag, it will only escape the 1st occurence and leaving the following ones as is.

  if (/[\t\f\r\n\b]/g.test(value)) {
    const codes = ['\f', '\r', '\n', '\t', '\b']
    const replaceCodes = ['\\f', '\\r', '\\n', '\\t', '\\b']
    for (let i = 0; i < codes.length; i++) {
      value = value.replace(new RegExp(codes[i]), replaceCodes[i])
    }
  }

For example;

// Input
const foo = ['Test\nthis\nstuff];

// Output
const foo = JSON.parse('["Test\\nthis\nstuff"]');

Using new RegExp(codes[i], 'g') should probably solve it.

Suppress error messages

This plugin is super noisy, complaining about the vast majority of non-serializable object literals in my apps.

I think running into a non serializable object literal should not be considered an error, and that the message should be removed.

JSON superset

I'm not sure this is a bug, but this behavior is not an ideal one, I think.

This plugin generates a source code that old JavaScript engine cannot parse when object includes U+2028 or U+2029 in a string. cf. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON#JavaScript_and_JSON_differences

before

const obj = {
  foo: "\u2028\u2029"
};

console.log(obj.foo);

after

const obj = JSON.parse('{"foo":"โ€จโ€ฉ"}');
console.log(obj.foo);

When the code after conversion is run in node.js v8:

(function (exports, require, module, __filename, __dirname) { const obj = JSON.parse('{"foo":"
                                                                                     ^^^^^^^^^

SyntaxError: Invalid or unexpected token
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

According to MDN, the latest Edge seems to fail too.

About prettier

Great work!
This repository includes .prettierrc.js but it seems to be unused.
Indeed, contents of this repository is not formatted by prettier.

My editor detects existence of .prettierrc.js and automatically formats the code I'm editing, which made me struggle while working on #1.
Please either enable prettier in this repository, or remove .prettierrc.js.

In addition, automatic linting on commit would be very nice.

Thank you!

Cannot convert object with single quotes in string

This plugin fails to convert following object literal:

const obj = {
  foo: "'abc'"
};

console.log(obj.foo);

result:

At 1 line (start) : The object wasn't converted (Unexpected token, expected "," (1:22) - make sure this is an expression.
> 1 | (JSON.parse('{"foo":"'abc'"}'))
    |             

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.