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

json-serialization

v0.0.6

Published

json-serialization is an extensible asynchronous JSON serialization library. json-serialization 是一个可扩展的异步 JSON 序列化库。

Downloads

4

Readme

json-serialization

English | 简体中文

介绍

json-serialization 是一个可扩展的异步 JSON 序列化库。

起步

基本用法

json-serialization 提供了以下方法:

| 方法 | 作用 | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------- | | stringify | 将一个 JavaScript 对象或值转换为 JSON 字符串, 如果指定了 serializer, 则可以选择性地替换值。 | | parse | 用来解析 JSON 字符串, 构造由字符串描述的 JavaScript 值或对象。 提供可选的 deserializer 用以在返回之前对所得到的对象执行变换 (操作)。 |

import { stringify, parse } from 'json-serialization';

// {"name":"memo","age":18}
var json = await stringify({ name: 'memo', age: 18 });

// {name: 'memo', age: 18}
var object = await parse(json);

循环引用

json-serialization 内置支持序列化和反序列化包含循环引用的数据结构。

在序列化过程中,循环引用会被转换为引用路径字符串。

以下是包含循环引用的数据结构示例:

var html = { name: 'html' };
var head = { name: 'head' };
var body = { name: 'body' };

head.parent = html;
body.parent = html;

head.next = body;
body.prev = head;

html.children = [head, body];

var json = await stringify(html, null, 4);

序列化后的 JSON 字符串为:

{
    "name": "html",
    "children": [
        {
            "name": "head",
            "parent": "$ref:[]",
            "next": {
                "name": "body",
                "parent": "$ref:[]",
                "prev": "$ref:[\"children\",\"0\"]"
            }
        },
        "$ref:[\"children\",\"0\",\"next\"]"
    ]
}

你也可以单独使用 json-serialization 提供的 replaceCircularReference 方法,得到一个以引用路径表示循环引用的新对象。

然后,通过 restoreCircularReference 方法恢复引用关系。

import { replaceCircularReference, restoreCircularReference } from 'json-serialization';

var replacedObject = replaceCircularReference(html);

var json = JSON.stringify(replacedObject);

var circularObject = restoreCircularReference(JSON.parse(json));

扩展序列化规则

json-serialization 支持通过提供 DeserializerSerializer 来自定义来扩展序列化和反序列化规则。

type Serializer = (this: any, key: string, value: any) => any | Promise<any>;
type Deserializer = (this: any, key: string, value: any) => any | Promise<any>;

function stringify(
    value: any,
    serializer?: null | undefined | Serializer | (null | undefined | Serializer)[],
    space?: number,
): Promise<string>;

function parse(
    text: string,
    deserializer?: null | undefined | Deserializer | (null | undefined | Deserializer)[],
): Promise<any>;

Serializer 类似于 JSON.stringifyreplacer 参数,Deserialize 类似于 JSON.parsereviver 参数。

以下示例展示如何将 bigint 序列化为字符串,以及如何进行反序列化。

import type { Serializer, Deserializer } from 'json-serialization';

const BigIntSerializer: Serializer = function (key, value: bigint | string | any) {
    switch (typeof value) {
        case 'bigint':
            return 'b' + String(value);
        case 'string':
            return 's' + value;
        default:
            return value;
    }
};

const BigIntDeserializer: Deserializer = function (key, value: string) {
    switch (value[0]) {
        case 's':
            return value.slice(1);
        case 'b':
            return BigInt(value.slice(1));
        default:
            return value;
    }
};

为了和普通的字符串区分, 我们分别加上一个字符前缀, b 表示 bigint, s 表示 string。 那么 memo 被序列化为 smemo, 18n 被序列化为 b18, 解析时再依据前缀判断出原来的类型和值。

// {"name":"smemo","age":"b18"}
var json = await stringify({ name: 'memo', age: 18n }, [BigIntSerializer]);

// {name: 'memo', age: 18}
var object = await parse(json, [BigIntDeserializer]);

当指定多个序列化器或反序列化器件时,它们会被串行调用(前一个序列化器的返回值作为下一个序列化器的入参)。 请确保同一组序列化器和反序列化器在两个列表中的书写顺序一致。

许可

MIT