Coder Social home page Coder Social logo

json2ts's Introduction

Json2ts

Convert JSON to ts type by compiler

English | 中文

json-parse > transform > codegen

online link

vscode plugin

plugin

github

Features

  • support level nesting
  • support array parse
  • support remark parse
  • more flexible. support key with double quotes or single quotes or no quotes

Install

npm i @cyly/json2ts

// or

yarn add @cyly/json2ts

// or

pnpm i @cyly/json2ts

// or

<script src="index.umd.min.js"></script>

json2ts.json2ts(`{ name: 'apha' }`, {
    semicolon: true
});

Document

json2ts

import json2ts from '@cyly/json2ts'

const json = `{
  "a": 123,
  "b": {
    "c": "123"
  },
  d: [1, 2, 3]
}`

const result = json2ts(json, {
  semicolon: true,
})

options

splitType

boolean. Default:true. split Object, if false ,will define new TYPE, then use this TYPE name in the result

parseArray

boolean. Default:false. parse array. false will return Array< any >, otherwise return Array< number | string ... >

required

boolean. Default:true. key is required or not. if false will return { a?: number}

semicolon

boolean. Default:false. with semicolon end. if true will return { a: number; b: string; }, otherwise will return { a: number b: string }

typePrefix

string. Default:''. type name prefix.exp: config User, name will be UserKeyName$0

typeSuffix

string. Default:Type. type name suffix. exp: config Temp,name will be KeyName$0Temp

indent

number. Default:2. output indent format.

comment

'inline' | 'block' | false. Default:false. output with comment.

optimizeArrayOptional

boolean. Default:false. optimize Object in Array. e.g. [{a: 1, b: 3}, {b: 2}] will be Array<{a: number; b?: number}>

genType

'type' | 'interface'. Default:type. output type or interface

parse

import { parse } from '@cyly/json2ts'

const json = `{
  "a": 123,
  "b": {
    "c": "123"
  },
  d: [1, 2, 3]
}`

const ast = parse(json)

traverser

import { traverser, STRING_TYPE, ARRAY_TYPE } from '@cyly/json2ts'

const json = `{
  "a": 123,
  "b": {
    "c": "123"
  },
  d: [1, 2, 3]
}`

const ast = parse(json)

traverser(ast, {
  [STRING_TYPE]: {
    entry(node, parent) {},
    exit(node, parent) {},
  },
  [ARRAY_TYPE]: {
    entry(node, parent) {},
    exit(node, parent) {},
  },
})
{
  "a": 123,
  "b": {
    "c": "123"
  },
  d: [1, 2, 3]
}

=>

{
    "key": "root",
    "type": "Root",
    "value": [{
        "key": "a",
        "value": "123",
        "type": "number",
        "loc": {
            "start": {
                "offset": 1,
                "column": 2,
                "line": 1
            },
            "end": {
                "offset": 8,
                "column": 9,
                "line": 1
            },
            "source": "\"a\":123"
        }
    },
    {
        "key": "b",
        "value": [{
            "key": "c",
            "value": "123",
            "type": "string",
            "loc": {
                "start": {
                    "offset": 14,
                    "column": 15,
                    "line": 1
                },
                "end": {
                    "offset": 23,
                    "column": 24,
                    "line": 1
                },
                "source": "\"c\":\"123\""
            }
        }],
        "type": "Object",
        "loc": {
            "start": {
                "offset": 9,
                "column": 10,
                "line": 1
            },
            "end": {
                "offset": 24,
                "column": 25,
                "line": 1
            },
            "source": "\"b\":{\"c\":\"123\"}"
        }
    },
    {
        "key": "d",
        "value": [{
            "key": "$ARRAY_ITEM$",
            "value": "1",
            "type": "number",
            "loc": {
                "start": {
                    "offset": 30,
                    "column": 31,
                    "line": 1
                },
                "end": {
                    "offset": 31,
                    "column": 32,
                    "line": 1
                },
                "source": "1"
            }
        },
        {
            "key": "$ARRAY_ITEM$",
            "value": "2",
            "type": "number",
            "loc": {
                "start": {
                    "offset": 32,
                    "column": 33,
                    "line": 1
                },
                "end": {
                    "offset": 33,
                    "column": 34,
                    "line": 1
                },
                "source": "2"
            }
        },
        {
            "key": "$ARRAY_ITEM$",
            "value": "3",
            "type": "number",
            "loc": {
                "start": {
                    "offset": 34,
                    "column": 35,
                    "line": 1
                },
                "end": {
                    "offset": 35,
                    "column": 36,
                    "line": 1
                },
                "source": "3"
            }
        }],
        "type": "Array",
        "loc": {
            "start": {
                "offset": 25,
                "column": 26,
                "line": 1
            },
            "end": {
                "offset": 36,
                "column": 37,
                "line": 1
            },
            "source": "\"d\":[1,2,3]"
        }
    }]
}

=>

{
  a: number,
  b: {
    c: string
  },
  d: Array< number >;
}

json2ts's People

Contributors

erhsilence avatar patrickchen928 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

Watchers

 avatar

json2ts's Issues

Escaped quotes in a string will cause parsing errors.

Input Result
{ 
  name: "\""
}
Cannot read properties of null (reading '0')
{ 
  name: "\"\"\"\"\"\"\""
}
value is illegal
{
  "a":"{\"hello\":1}",
  "b": "\"",
  "c": "\\\\\\\\\\\\\"
}
type Result$0Type = {
  a: string
  hello\": number
}

Regarding the regular expressions used for string parsing, it can be optimized like this:

function parseString(context: ParserContext) {
  const s = context.source[0];
- const match = new RegExp(`^${s}((?:\\.|[^\\${s}])*)${s}`).exec(context.source);
+ const match = /^(.)((.*?)(?<!\\)|\\+)\1/.exec(context.source);
  advanceBy(context, match[0].length);
  return match[1];
}

Tested by regex101: https://regex101.com/r/16yhH6/1

Problems in special comment cases

Found some problems caused by comments. Of course, normally we don't do this intentionally 😃 .

Case Input Result
Empty comment
{
  "foo": 1 //
}
type Result$0Type = {
  foo: number // }
}
Empty comment in array item
{
  "foo": [{
    "bar": 1 //
  }],
}
{
  "foo": [{
    "bar": 1 //
    "baz": 2
  }],
}
array should be closed
type Result$0Type = {
  foo: Array< {
    bar: number // "baz": 2
  } >
}
Comment with \t
(between the letters a and b)
{
  "foo": 1, // aaaaa	bbbbb
}
value is illegal

解析小数时返回类型异常

你好,我在你提供的在线示例中解析类型的时候,发现小数无法被正常解析。

这是我的数据:

{
    "unitPrice": 0.6,
      "value": "string"
  }

得到的结果是:

interface Result$0Type {
  unitPrice: number
  .6,
      "value": string
}

预期的结果应该是:

interface Result$0Type {
  unitPrice: number
  value: string
}

返回数据类型问题

请教下大佬,目前我使用插件得到的是一个interface字符串,能返回一个interface变量吗?

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.