변환기 - 범위 지정, 전역

  • 릴리스 버전: Yokohama
  • 업데이트 날짜 2025년 01월 30일
  • 읽기9분
  • 변환기 API는 정의된 규칙 세트를 사용하여 구조화된 JSON 또는 XML 소스 콘텐츠를 구문 분석하고 구조화된 키-값 쌍 출력으로 변환하는 메서드를 제공합니다.

    이 API는 TransformerDefinitionTransformerRuleList API와 함께 작동합니다. 이러한 API는 구조화된 JSON 문서의 XML 노드 또는 엔터티를 이름-값 쌍의 출력으로 변환합니다. 문자열, 숫자 및 기타 배열과 같이 배열 내의 개체 및 요소를 포함하여 지원되는 JSON 엔터티입니다.

    • TransformerRuleList API를 사용하면 출력에 포함할 원본 문서의 데이터와 원본 데이터를 변환하는 방법을 정의하는 변환 규칙 목록을 만들 수 있습니다.

    • TransformerDefinition API는 변환 규칙 목록을 JSON/XML 레코드 경로와 연관시켜 재사용 가능한 변환 정의 오브젝트를 정의합니다. 변환 정의 개체를 사용하여 하나 이상의 원본 문서를 변환할 수 있습니다.

    • 변환기 API는 지정된 변환 규칙 목록을 사용하여 한 번에 하나의 데이터 엔터티로 실제 데이터 변환을 수행하여 원하는 출력 데이터를 생성합니다.

    범위가 지정된 서버 스크립트와 전역 서버 스크립트 모두에서 Transformer 클래스를 사용할 수 있습니다. 이 클래스를 사용하는 경우 sn_tfrm 네임스페이스 식별자를 사용합니다. 인스턴스에서 이 API를 사용할 수 있으려면 먼저 Transformation Service 플러그인(com.glide.transform)을 활성화해야 합니다.

    다음 예제에서는 TransformerRuleList API를 사용하여 변환 규칙을 정의하고, TransformerDefinition API를 사용하여 변환 기준을 정의하고, Transformer API를 사용하여 실제로 변환을 수행하는 방법을 보여줍니다.

    이 코드 예제에서는 외부 JSON 기반 재고 세부 정보 문서를 검색하고, 해당 데이터를 테이블 형식 테이블로 변환하는 규칙을 만든 다음, 소스 문서를 한 번에 한 행씩 변환합니다. 다음은 변환되는 JSON 소스 문서의 스니펫입니다.

    {
      "NOW": {
        "quote": {
          "symbol": "NOW",
          "companyName": "ServiceNow Inc.",
          "primaryExchange": "New York Stock Exchange",
          "sector": "Technology",
          "open": 166.78,
          "openTime": 1522935000556,
          "close": 165.77,
          "changePercent": 0.00656,
           ...
         },
     ...}
    var stockAPI = new sn_ws.RESTMessageV2('Stock Details', 'Default GET'); 
    var response = stockAPI.execute(); 
    var responseBody = response.getBody(); // obtain the source JSON document
    
    /* Define the list of rules to use to transform the acquired JSON stock detail 
    information into a tabular table */
    
    var transformerRuleList = new sn_tfrm.TransformerRuleList() // instantiate the rule list object
      .fromJSON() // indicate that the source document is JSON
      .addRule('ticker', '$.quote.symbol') // add a rule to copy the value in the "symbol" field of the source document to the ticker field in the output document (no changes)
      .addRule('change_percentage', '$.quote.changePercent') // copy the "changePercent" field from source into the change_percentage field of output document
      .thenMultiply('100') // multiply the change_percentage value by 100
      .thenRoundDown('0') // addthen round it down to a whole number 
      .addRule('close_price', '$.quote.close') // copy the "close" field to the close_price field in the 21=-[';output
      .thenAdaptCurrency('USD', false) // attach the US dollar code to the close_price field, but do not display the symbol
      .addRule('summary') // add a blank "summary" field to the output (no corresponding source field)
      .thenConcat('Shares of ') // in the summary field concatenate the string "Shares of "
      .thenConcatSymbol('ticker') // then concatenate the "ticker" field from the source document
      .thenConcat(' closed at ') // then concatenate the string " closed at "
      .thenConcatSymbol('close_price'); // then concatenate the "close_price" field from the source document
    
    // Create a transformer definition that associates the rule list to use and the record path of the set of records in the source document to transform.  
    var path = '$.*'; 
    var transformerDefinition = new sn_tfrm.TransformerDefinition(transformerRuleList, path);
     
    // Instantiate the transformer object.
    var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody); 
    
    // Transform the source data, one row at a time, until all rows are processed.
    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());
    } 

    출력:

     {ticker: "Now", change_percentage: "0", close_price: "165.77 USD", summary: "Shares of Now closed at 165.77" }

    변환기 - Transformer(Object transformerDefinition, String document)

    Transformer 개체(생성자)를 인스턴스화합니다.

    표 1. 매개변수
    이름 유형 설명
    변환기 정의 객체 콘텐츠 변환을 설명하는 객체입니다. 규칙 목록 및 JSONPath/XPath 기록 경로를 포함합니다.

    TransformerRuleList()TransformerDefinition() API를 사용하여 이 오브젝트를 생성하십시오.

    문서 문자열 번역할 소스 문서입니다.
    var stockAPI = new sn_ws.RESTMessageV2('Stock Details', 'Default GET'); 
    var response = stockAPI.execute(); 
    var responseBody = response.getBody(); 
    
    var transformerRuleList = new sn_tfrm.TransformerRuleList()
      .fromJSON()
      .addRule('ticker', 'quote.symbol') 
      .addRule('change_percentage', 'quote.change') 
      .thenMultiply('100') 
      .thenRoundDown('0') 
      .addRule('close_price', 'quote.close') 
      .thenAdaptCurrency('USD', false) 
      .addRule('summary') 
      .thenConcat('Shares of ') 
      .thenConcatSymbol('ticker') 
      .thenConcat(' closed at ') 
      .thenConcatSymbol('close') 
    
     
    var path = '$.*'; 
    var transformerDefinition = new sn_tfrm.TransformerDefinition(transformerRuleList, path); 
    var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody); 
    
    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());
    }

    변환기 - getRow()

    마지막 변환의 결과 행을 반환합니다(또는 행이 없으면 null).

    표 2. 매개변수
    이름 유형 설명
    없음
    표 3. 반환
    유형 설명
    객체 변환된 하나의 데이터 행/노드를 포함하는 객체입니다.
    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());
    

    출력:

     {ticker: "Now", change_percentage: "0", close_price: "165.77 USD", summary: "Shares of Now closed at 165.77" }

    변환기 - transform()

    소스 문서에서 사용 가능한 다음 행/노드를 변환합니다.

    표 4. 매개변수
    이름 유형 설명
    없음
    표 5. 반환
    유형 설명
    부울 변환할 유효한 다음 행이 있는지 여부를 나타내는 플래그입니다.
    • true: 유효한 다음 행
    • false: 추가 행 없음
    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());
    

    출력:

     {ticker: "Now", change_percentage: "0", close_price: "165.77 USD", summary: "Shares of Now closed at 165.77" }