npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@karosli/quicktype

v23.0.10

Published

![](https://raw.githubusercontent.com/quicktype/quicktype/master/media/quicktype-logo.svg?sanitize=true)

Downloads

6

Readme

npm version Build status

quicktype generates strongly-typed models and serializers from JSON, JSON Schema, TypeScript, and GraphQL queries, making it a breeze to work with JSON type-safely in many programming languages.

Supported Inputs

| JSON | JSON API URLs | JSON Schema | | ---- | ------------- | ----------------------------------------------------- |

| TypeScript | GraphQL queries | | ---------- | --------------- |

Target Languages

| Ruby | JavaScript | Flow | Rust | Kotlin | | ---------------------------------------- | -------------------------------------------- | ---------------------------------------- | ---------------------------------------- | -------------------------------------------- |

| Dart | Python | C# | Go | C++ | | ---------------------------------------- | -------------------------------------------- | ------------------------------------ | ------------------------------------ | -------------------------------------- |

| Java | TypeScript | Swift | Objective-C | Elm | | ---------------------------------------- | -------------------------------------------- | ------------------------------------------ | ----------------------------------------------- | -------------------------------------- |

| JSON Schema | Pike | Prop-Types | Haskell | PHP | | ------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------- | ---------------------------------------------- | -------------------------------------- |

Missing your favorite language? Please implement it!

Installation

There are many ways to use quicktype. app.quicktype.io is the most powerful and complete UI. The web app also works offline and doesn't send your sample data over the Internet, so paste away!

For the best CLI, we recommend installing quicktype globally via npm:

npm install -g quicktype

Other options:

* limited functionality

Using quicktype

# Run quicktype without arguments for help and options
quicktype

# quicktype a simple JSON object in C#
echo '{ "name": "David" }' | quicktype -l csharp

# quicktype a top-level array and save as Go source
echo '[1, 2, 3]' | quicktype -o ints.go

# quicktype a sample JSON file in Swift
quicktype person.json -o Person.swift

# A verbose way to do the same thing
quicktype \
  --src person.json \
  --src-lang json \
  --lang swift \
  --top-level Person \
  --out Person.swift

# quicktype a directory of samples as a C++ program
# Suppose ./blockchain is a directory with files:
#   latest-block.json transactions.json marketcap.json
quicktype ./blockchain -o blockchain-api.cpp

# quicktype a live JSON API as a Java program
quicktype https://api.somewhere.com/data -o Data.java

Generating code from JSON schema

The recommended way to use quicktype is to generate a JSON schema from sample data, review and edit the schema, commit the schema to your project repo, then generate code from the schema as part of your build process:

# First, infer a JSON schema from a sample.
quicktype pokedex.json -l schema -o schema.json

# Review the schema, make changes,
# and commit it to your project repo.

# Finally, generate model code from schema in your
# build process for whatever languages you need:
quicktype -s schema schema.json -o src/ios/models.swift
quicktype -s schema schema.json -o src/android/Models.java
quicktype -s schema schema.json -o src/nodejs/Models.ts

# All of these models will serialize to and from the same
# JSON, so different programs in your stack can communicate
# seamlessly.

Generating code from TypeScript (Experimental)

You can achieve a similar result by writing or generating a TypeScript file, then quicktyping it. TypeScript is a typed superset of JavaScript with simple, succinct syntax for defining types:

interface Person {
    name: string;
    nickname?: string; // an optional property
    luckyNumber: number;
}

You can use TypeScript just like JSON schema was used in the last example:

# First, infer a TypeScript file from a sample (or just write one!)
quicktype pokedex.json -o pokedex.ts --just-types
# Review the TypeScript, make changes, etc.
quicktype pokedex.ts -o src/ios/models.swift

Calling quicktype from JavaScript

You can use quicktype as a JavaScript function within node or browsers. First add the quicktype-core package:

$ npm install quicktype-core

In general, first you create an InputData value with one or more JSON samples, JSON schemas, TypeScript sources, or other supported input types. Then you call quicktype, passing that InputData value and any options you want.

import {
    quicktype,
    InputData,
    jsonInputForTargetLanguage,
    JSONSchemaInput,
    FetchingJSONSchemaStore
} from "quicktype-core";

async function quicktypeJSON(targetLanguage, typeName, jsonString) {
    const jsonInput = jsonInputForTargetLanguage(targetLanguage);

    // We could add multiple samples for the same desired
    // type, or many sources for other types. Here we're
    // just making one type from one piece of sample JSON.
    await jsonInput.addSource({
        name: typeName,
        samples: [jsonString]
    });

    const inputData = new InputData();
    inputData.addInput(jsonInput);

    return await quicktype({
        inputData,
        lang: targetLanguage
    });
}

async function quicktypeJSONSchema(targetLanguage, typeName, jsonSchemaString) {
    const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore());

    // We could add multiple schemas for multiple types,
    // but here we're just making one type from JSON schema.
    await schemaInput.addSource({ name: typeName, schema: jsonSchemaString });

    const inputData = new InputData();
    inputData.addInput(schemaInput);

    return await quicktype({
        inputData,
        lang: targetLanguage
    });
}

async function main() {
    const { lines: swiftPerson } = await quicktypeJSON("swift", "Person", jsonString);
    console.log(swiftPerson.join("\n"));

    const { lines: pythonPerson } = await quicktypeJSONSchema("python", "Person", jsonSchemaString);
    console.log(pythonPerson.join("\n"));
}

main();

The argument to quicktype is a complex object with many optional properties. Explore its definition to understand what options are allowed.

Contributing

quicktype is Open Source and we love contributors! In fact, we have a list of issues that are low-priority for us, but for which we'd happily accept contributions. Support for new target languages is also strongly desired. If you'd like to contribute, need help with anything at all, or would just like to talk things over, come join us on Slack.

Setup, Build, Run

quicktype is implemented in TypeScript and requires nodejs and npm to build and run.

First, install typescript globally via npm:

Clone this repo and do:

macOS / Linux

nvm use
npm install
script/quicktype # rebuild (slow) and run (fast)

Windows

npm install --ignore-scripts # Install dependencies
npm install -g typescript # Install typescript globally
tsc --project src/cli # Rebuild
node dist\cli\index.js # Run

Edit

Install Visual Studio Code, open this workspace, and install the recommended extensions:

code . # opens in VS Code

Live-reloading for quick feedback

When working on an output language, you'll want to view generated output as you edit. Use npm start to watch for changes and recompile and rerun quicktype for live feedback. For example, if you're developing a new renderer for fortran, you could use the following command to rebuild and reinvoke quicktype as you implement your renderer:

npm start -- "--lang fortran pokedex.json"

The command in quotes is passed to quicktype, so you can render local .json files, URLs, or add other options.

Test

# Run full test suite
npm run test

# Test a specific language (see test/languages.ts)
FIXTURE=golang npm test

# Test a single sample or directory
FIXTURE=swift npm test -- pokedex.json
FIXTURE=swift npm test -- test/inputs/json/samples

https://segmentfault.com/a/1190000021639944

运行补充

本地编译

npm run build

json 样例

test.json

{
    "item_id": 111,
    "store": {
        "name": "背景",
        "thumbnail": "http://",
        "imgurl": "",
        "desc": "",
        "price": [
            {
                "id": 5,
                "num": 8,
                "discount": 8
            }
        ],
        "discount_start": 1677741857,
        "discount_end": 1677741857
    },
    "info": {
        "anim_type": 1,
        "anim_url": ""
    }
}

把 json 转成 OC-YYModel 格式

script/quicktype --src test.json --src-lang json --lang objc-yymodel --class-prefix KK --out KKBGItem.m
# 简写
script/quicktype test.json -l objc-yymodel --class-prefix KK -o KKBGItem.m

运行结果:

// KKBGItem.h
#import <Foundation/Foundation.h>

@class KKBGItem;
@class KKInfo;
@class KKStore;
@class KKPrice;

NS_ASSUME_NONNULL_BEGIN

@interface KKBGItem : NSObject
@property (nonatomic, assign) NSInteger itemID;
@property (nonatomic, strong) KKStore *store;
@property (nonatomic, strong) KKInfo *info;
@end

@interface KKInfo : NSObject
@property (nonatomic, assign) NSInteger animType;
@property (nonatomic, copy)   NSString *animURL;
@end

@interface KKStore : NSObject
@property (nonatomic, copy)   NSString *name;
@property (nonatomic, copy)   NSString *thumbnail;
@property (nonatomic, copy)   NSString *imgurl;
@property (nonatomic, copy)   NSString *desc;
@property (nonatomic, copy)   NSArray<KKPrice *> *price;
@property (nonatomic, assign) NSInteger discountStart;
@property (nonatomic, assign) NSInteger discountEnd;
@end

@interface KKPrice : NSObject
@property (nonatomic, assign) NSInteger identifier;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, assign) NSInteger discount;
@end

NS_ASSUME_NONNULL_END

// KKBGItem.m
#import "KKBGItem.h"

NS_ASSUME_NONNULL_BEGIN

@implementation KKBGItem

+ (NSDictionary *)modelCustomPropertyMapper
{
    return @{
        @"itemID": @"item_id", 
        @"store": @"store", 
        @"info": @"info", 
    };
}

@end

@implementation KKInfo

+ (NSDictionary *)modelCustomPropertyMapper
{
    return @{
        @"animType": @"anim_type", 
        @"animURL": @"anim_url", 
    };
}

@end

@implementation KKStore

+ (NSDictionary *)modelCustomPropertyMapper
{
    return @{
        @"name": @"name", 
        @"thumbnail": @"thumbnail", 
        @"imgurl": @"imgurl", 
        @"desc": @"desc", 
        @"price": @"price", 
        @"discountStart": @"discount_start", 
        @"discountEnd": @"discount_end", 
    };
}

+ (NSDictionary *)modelContainerPropertyGenericClass
{
    return @{
        @"price": [KKPrice class],
    };
}

@end

@implementation KKPrice

+ (NSDictionary *)modelCustomPropertyMapper
{
    return @{
        @"identifier": @"id", 
        @"num": @"num", 
        @"discount": @"discount", 
    };
}

@end

NS_ASSUME_NONNULL_END

把 json 转成 swift-YYModel 格式

script/quicktype --src test.json --src-lang json --lang swift-yymodel --type-prefix KK --out KKBGItem.swift
# 简写
script/quicktype test.json -l swift-yymodel --type-prefix KK -o KKBGItem.swift

运行结果:

import Foundation

// MARK: - KKBGItem
@objcMembers class KKBGItem: NSObject, YYModel {
    var itemID: Int = 0
    var store: KKStore?
    var info: KKInfo?

    static func modelCustomPropertyMapper() -> [String : Any]? {
        return [
            "itemID": "item_id", 
            "store": "store", 
            "info": "info", 
        ]
    }
}

// MARK: - KKInfo
@objcMembers class KKInfo: NSObject, YYModel {
    var animType: Int = 0
    var animURL: String = ""

    static func modelCustomPropertyMapper() -> [String : Any]? {
        return [
            "animType": "anim_type", 
            "animURL": "anim_url", 
        ]
    }
}

// MARK: - KKStore
@objcMembers class KKStore: NSObject, YYModel {
    var name: String = ""
    var thumbnail: String = ""
    var imgurl: String = ""
    var desc: String = ""
    var price: [KKPrice] = []
    var discountStart: Int = 0
    var discountEnd: Int = 0

    static func modelCustomPropertyMapper() -> [String : Any]? {
        return [
            "name": "name", 
            "thumbnail": "thumbnail", 
            "imgurl": "imgurl", 
            "desc": "desc", 
            "price": "price", 
            "discountStart": "discount_start", 
            "discountEnd": "discount_end", 
        ]
    }

    static func modelContainerPropertyGenericClass() -> [String : Any]? {
        return [
            "price": KKPrice.self,
        ]
    }
}

// MARK: - KKPrice
@objcMembers class KKPrice: NSObject, YYModel {
    var id: Int = 0
    var num: Int = 0
    var discount: Int = 0

    static func modelCustomPropertyMapper() -> [String : Any]? {
        return [
            "id": "id", 
            "num": "num", 
            "discount": "discount", 
        ]
    }
}

全局安装

sudo npm install -g @karosli/quicktype