@axync/extract-json

中文文档
1.1.3发布于 2025/06/05MITTypeScriptES Module零依赖近 30 天下载 4678

An utility to extract JSON object and array from a string.

原始使用文档
文档目录17 节
  1. Overview
  2. Installation
  3. Usage
  4. Example (Async)
  5. Example (Sync)
  6. Example (Async Streaming)
  7. Extract with Limit
  8. API
  9. extractJson(rawString: string, limit?: number): Promise<T[]>
  10. extractJsonSync(rawString: string, limit?: number): T[]
  11. extractStream(rawString: string): AsyncGenerator<T>
  12. How It Works
  13. Performance
  14. Test Environment
  15. Observations
  16. Limitations
  17. License

@axync/extract-json

Test

Overview

@axync/extract-json is a powerful utility designed to extract valid JSON objects and arrays from raw text. Whether you're working with large text data, processing logs, or parsing responses from Large Language Models (LLMs), this package helps you efficiently extract structured JSON data from unstructured strings.

Key features include:

  • Asynchronous and Streaming Support: Process large strings incrementally without blocking the event loop.
  • Flexible JSON Extraction: Extract multiple JSON objects or arrays from mixed or noisy text.
  • Real-Time Data Processing: Ideal for real-time applications like log parsing or API response handling.
  • Error Resilience: Skips invalid JSON gracefully while continuing to parse valid data.

Note: This package focuses on extracting JSON objects ({}) and arrays ([]) only. Other JSON types like strings, numbers, or booleans are not supported.

With @axync/extract-json, you can seamlessly integrate JSON extraction into your workflows, making it an essential tool for developers working with unstructured text or LLM outputs.

Installation

You can install the package using npm:

npm install @axync/extract-json

Usage

The primary functions provided by this package are extractJson (asynchronous) and extractJsonSync (synchronous), which allow you to extract JSON objects and arrays from a raw string.

Example (Async)

import { extractJson } from '@axync/extract-json';

const rawString = `
  Here is some text before a JSON object: {"key": "value"} 
  and another one: {"anotherKey": 123} and here is an array: [1, 2, 3]
`;

const jsonObjects = await extractJson(rawString);

console.log(jsonObjects);
// Output: [{ "key": "value" }, { "anotherKey": 123 }, [1, 2, 3]]

Example (Sync)

import { extractJsonSync } from '@axync/extract-json';

const rawString = `
  Here is some text before a JSON object: {"key": "value"} 
  and another one: {"anotherKey": 123} and here is an array: [1, 2, 3]
`;

const jsonObjects = extractJsonSync(rawString);

console.log(jsonObjects);
// Output: [{ "key": "value" }, { "anotherKey": 123 }, [1, 2, 3]]

Example (Async Streaming)

The extractStream function allows you to process JSON objects incrementally, which is useful for large strings or real-time data processing.

import { extractStream } from '@axync/extract-json';

const rawString = `
  {"key1": "value1"} {"key2": "value2"} {"key3": "value3"}
`;

for await (const json of extractStream(rawString)) {
  console.log(json);
}
// Output:
// { key1: "value1" }
// { key2: "value2" }
// { key3: "value3" }

Extract with Limit

You can also specify a limit to control the number of JSON objects or arrays extracted:

Async

const jsonObjects = await extractJson(rawString, 2);

console.log(jsonObjects);
// Output: [{ "key": "value" }, { "anotherKey": 123 }]

Sync

const jsonObjects = extractJsonSync(rawString, 2);

console.log(jsonObjects);
// Output: [{ "key": "value" }, { "anotherKey": 123 }]

API

extractJson(rawString: string, limit?: number): Promise<T[]>

  • rawString: The string containing potential JSON objects or arrays.
  • limit: (Optional) The maximum number of JSON objects/arrays to extract. Defaults to Infinity.

Returns: A Promise that resolves to an array of extracted JSON objects and arrays.


extractJsonSync(rawString: string, limit?: number): T[]

  • rawString: The string containing potential JSON objects or arrays.
  • limit: (Optional) The maximum number of JSON objects/arrays to extract. Defaults to Infinity.

Returns: An array of extracted JSON objects and arrays.


extractStream(rawString: string): AsyncGenerator<T>

  • rawString: The string containing potential JSON objects or arrays.

Returns: An AsyncGenerator that yields JSON objects and arrays as they are parsed.

How It Works

  1. Direct Parsing: The JsonExtractor class first attempts to directly parse the entire string as JSON.

  2. Finding Start Indexes: If direct parsing fails, it scans the string for potential start indexes of JSON objects ({, [) and arrays.

  3. Parsing Substrings: The class then attempts to parse substrings starting from each identified index, searching for valid JSON objects and arrays.

  4. Streaming: The extractStream method processes the string incrementally and yields JSON objects as they are parsed.

Performance

Performance tests were conducted to evaluate the efficiency of the three primary functions provided by @axync/extract-json. Below are the results for processing 100,000 JSON objects and an array:

  • extractJson: Processed in approximately 86.25ms.
  • extractJsonSync: Processed in approximately 78.93ms.
  • extractStream: Processed in approximately 108.98ms.

Test Environment

  • CPU: 13th Gen Intel(R) Core(TM) i9-13900K, 24 cores, 3.0 GHz

Observations

  • extractJsonSync is the fastest for synchronous operations but blocks the event loop.
  • extractJson provides asynchronous processing, making it suitable for non-blocking operations.
  • extractStream is ideal for streaming large data incrementally.

Limitations

  • This package only extracts JSON objects ({}) and arrays ([]). It does not extract other JSON data types like strings, numbers, or booleans.

License

This project is licensed under the MIT License.

版本与发布记录

@axync/extract-json 共发布 7 个版本,首次发布于 2024/09/03;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.1.3latest2025/06/051.4 年前
1.1.22025/06/051.4 年前
1.1.12025/05/131.5 年前
1.1.02025/05/131.5 年前
1.0.22024/09/072 年前
1.0.12024/09/032 年前

关于 @axync/extract-json 的常见问题

@axync/extract-json 是什么?

An utility to extract JSON object and array from a string.

如何安装 @axync/extract-json?

在项目目录运行 npm install @axync/extract-json,或使用 pnpm add / yarn add / bun add。

@axync/extract-json 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@axync/extract-json 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@axync/extract-json 可以商用吗?

@axync/extract-json 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@axync/extract-json 的下载量有多少?

根据 npm 官方下载统计,@axync/extract-json 在 2026/10/08 – 2026/11/06 这 30 天内被下载 4,678 次,日均约 156 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@axync/extract-json 还在维护吗?

最新版本 1.1.3 发布于 2025/06/05(1.4 年前);至今共发布 7 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/09/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。