Skip to main content
이 JSON 분할기는 청크 크기를 제어하면서 JSON 데이터를 분할합니다. JSON 데이터를 깊이 우선으로 탐색하여 더 작은 JSON 청크를 만듭니다. 중첩된 JSON 객체를 가능한 한 온전하게 유지하려고 시도하지만, 청크를 min_chunk_size와 max_chunk_size 사이로 유지하기 위해 필요하다면 분할합니다. 값이 중첩된 JSON이 아니라 매우 긴 문자열인 경우, 해당 문자열은 분할되지 않습니다. 청크 크기에 대한 엄격한 제한이 필요한 경우, 이러한 청크에 대해 Recursive Text 분할기와 함께 사용하는 것을 고려하세요. 리스트를 먼저 JSON(dict)으로 변환한 다음 분할하는 선택적 전처리 단계가 있습니다.
  1. 텍스트 분할 방식: JSON 값 단위
  2. 청크 크기 측정 방식: 문자 수 기준
pip install -qU langchain-text-splitters
먼저 일부 JSON 데이터를 불러옵니다:
import json

import requests

# This is a large nested json object and will be loaded as a python dict
json_data = requests.get("https://api.smith.langchain.com/openapi.json").json()

기본 사용법

청크 크기를 제한하려면 max_chunk_size를 지정하세요:
from langchain_text_splitters import RecursiveJsonSplitter

splitter = RecursiveJsonSplitter(max_chunk_size=300)
JSON 청크를 얻으려면 .split_json 메서드를 사용하세요:
# Recursively split json data - If you need to access/manipulate the smaller json chunks
json_chunks = splitter.split_json(json_data=json_data)

for chunk in json_chunks[:3]:
    print(chunk)
{'openapi': '3.1.0', 'info': {'title': 'LangSmith', 'version': '0.1.0'}, 'servers': [{'url': 'https://api.smith.langchain.com', 'description': 'LangSmith API endpoint.'}]}
{'paths': {'/api/v1/sessions/{session_id}': {'get': {'tags': ['tracer-sessions'], 'summary': 'Read Tracer Session', 'description': 'Get a specific session.', 'operationId': 'read_tracer_session_api_v1_sessions__session_id__get'}}}}
{'paths': {'/api/v1/sessions/{session_id}': {'get': {'security': [{'API Key': []}, {'Tenant ID': []}, {'Bearer Auth': []}]}}}}
LangChain Document 객체를 얻으려면 .create_documents 메서드를 사용하세요:
# The splitter can also output documents
docs = splitter.create_documents(texts=[json_data])

for doc in docs[:3]:
    print(doc)
page_content='{"openapi": "3.1.0", "info": {"title": "LangSmith", "version": "0.1.0"}, "servers": [{"url": "https://api.smith.langchain.com", "description": "LangSmith API endpoint."}]}'
page_content='{"paths": {"/api/v1/sessions/{session_id}": {"get": {"tags": ["tracer-sessions"], "summary": "Read Tracer Session", "description": "Get a specific session.", "operationId": "read_tracer_session_api_v1_sessions__session_id__get"}}}}'
page_content='{"paths": {"/api/v1/sessions/{session_id}": {"get": {"security": [{"API Key": []}, {"Tenant ID": []}, {"Bearer Auth": []}]}}}}'
또는 .split_text를 사용하여 문자열 콘텐츠를 직접 얻을 수 있습니다:
texts = splitter.split_text(json_data=json_data)

print(texts[0])
print(texts[1])
{"openapi": "3.1.0", "info": {"title": "LangSmith", "version": "0.1.0"}, "servers": [{"url": "https://api.smith.langchain.com", "description": "LangSmith API endpoint."}]}
{"paths": {"/api/v1/sessions/{session_id}": {"get": {"tags": ["tracer-sessions"], "summary": "Read Tracer Session", "description": "Get a specific session.", "operationId": "read_tracer_session_api_v1_sessions__session_id__get"}}}}

리스트 콘텐츠의 청크 크기 관리 방법

이 예제의 청크 중 하나가 지정된 max_chunk_size 300보다 크다는 점에 주목하세요. 더 큰 청크 중 하나를 확인해보면 리스트 객체가 있음을 알 수 있습니다:
print([len(text) for text in texts][:10])
print()
print(texts[3])
[171, 231, 126, 469, 210, 213, 237, 271, 191, 232]

{"paths": {"/api/v1/sessions/{session_id}": {"get": {"parameters": [{"name": "session_id", "in": "path", "required": true, "schema": {"type": "string", "format": "uuid", "title": "Session Id"}}, {"name": "include_stats", "in": "query", "required": false, "schema": {"type": "boolean", "default": false, "title": "Include Stats"}}, {"name": "accept", "in": "header", "required": false, "schema": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Accept"}}]}}}}
JSON 분할기는 기본적으로 리스트를 분할하지 않습니다. JSON을 전처리하여 리스트 콘텐츠를 index:itemkey:val 쌍으로 갖는 dict로 변환하려면 convert_lists=True를 지정하세요:
texts = splitter.split_text(json_data=json_data, convert_lists=True)
청크의 크기를 살펴보겠습니다. 이제 모두 최대값 이하입니다:
print([len(text) for text in texts][:10])
[176, 236, 141, 203, 212, 221, 210, 213, 242, 291]
리스트는 dict로 변환되었지만, 여러 청크로 분할되더라도 필요한 모든 컨텍스트 정보를 유지합니다:
print(texts[1])
{"paths": {"/api/v1/sessions/{session_id}": {"get": {"tags": {"0": "tracer-sessions"}, "summary": "Read Tracer Session", "description": "Get a specific session.", "operationId": "read_tracer_session_api_v1_sessions__session_id__get"}}}}
# We can also look at the documents
docs[1]
Document(page_content='{"paths": {"/api/v1/sessions/{session_id}": {"get": {"tags": ["tracer-sessions"], "summary": "Read Tracer Session", "description": "Get a specific session.", "operationId": "read_tracer_session_api_v1_sessions__session_id__get"}}}}')

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I