JSONConverter

JSONConverter

JSON 파일 하나(또는 여러 개)를 받아서 텍스트 문서로 바꿔주는 변환 컴포넌트예요. 인덱싱 파이프라인의 시작 부분이나 PreProcessor 앞에 두고 쓰는 게 가장 흔한 자리예요.

출처: JSONConverter

본문

개요

JSONConverter는 하나 이상의 JSON 파일을 텍스트 문서로 바꿔요. 초기화할 때는 jq_schema나 content_key 파라미터 중 하나, 또는 둘 다를 반드시 넘겨줘야 해요.

jq_schema 파라미터는 JSON 파일에서 중첩된 데이터를 추출하는 필터예요. 필터 문법은 jq 문서를 참고하면 돼요. 설정하지 않으면 JSON 파일 전체를 그대로 사용해요.

content_key 파라미터는 추출된 데이터 중에서 어떤 키를 문서의 내용(content)으로 쓸지 지정해 줘요.

  • jq_schema와 content_key 둘 다 설정하면, jq_schema로 추출한 데이터 안에서 content_key를 찾아요. 객체가 아닌 데이터는 건너뛰어요.
  • jq_schema만 설정하면 추출된 값이 스칼라여야 하며, 객체나 배열은 건너뛰어요.
  • content_key만 설정하면 원본이 JSON 객체여야 해요. 아니면 건너뛰어요.

전체 파라미터 목록은 API reference를 확인해 보세요.

사용법

이 Converter를 쓰려면 jq 패키지를 설치해야 해요.

pip install jq

예시

간단한 컴포넌트 사용 예시예요.

import json

from haystack.components.converters import JSONConverter
from haystack.dataclasses import ByteStream

source = ByteStream.from_string(
    json.dumps({"text": "This is the content of my document"}),
)

converter = JSONConverter(content_key="text")
results = converter.run(sources=[source])
documents = results["documents"]
print(documents[0].content)
# 'This is the content of my document'

다음은 좀 더 복잡한 예시예요. jq_schema 문자열로 JSON 원본을 필터링하고, extra_meta_fields로 추가 메타데이터를 추출해요.

import json

from haystack.components.converters import JSONConverter
from haystack.dataclasses import ByteStream

data = {
    "laureates": [
        {
            "firstname": "Enrico",
            "surname": "Fermi",
            "motivation": "for his demonstrations of the existence of new radioactive elements produced "
            "by neutron irradiation, and for his related discovery of nuclear reactions brought about by"
            " slow neutrons",
        },
        {
            "firstname": "Rita",
            "surname": "Levi-Montalcini",
            "motivation": "for their discoveries of growth factors",
        },
    ],
}
source = ByteStream.from_string(json.dumps(data))
converter = JSONConverter(
    jq_schema=".laureates[]",
    content_key="motivation",
    extra_meta_fields={"firstname", "surname"},
)

results = converter.run(sources=[source])
documents = results["documents"]
print(documents[0].content)
# 'for his demonstrations of the existence of new radioactive elements produced by
# neutron irradiation, and for his related discovery of nuclear reactions brought
# about by slow neutrons'

print(documents[0].meta)
# {'firstname': 'Enrico', 'surname': 'Fermi'}

print(documents[1].content)
# 'for their discoveries of growth factors'

print(documents[1].meta)
# {'firstname': 'Rita', 'surname': 'Levi-Montalcini'}

더 알아보기 (Learn more)