> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kasoftware.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 函式

> ArcScript 函式格式化器，用於 CSV、JSON、XML 和實用操作，可在不需要管道輸入值的情況下生成輸出。

可以將函式視為一種特殊型別的格式化器，它會生成輸出值，但不像標準格式化器那樣需要輸入。函式可以單獨使用，也可以作為更復雜運算式的開頭，並在其後透過管道接入其他格式化器。例如，`[vault(foo)]` 可以單獨解析，也可以作為運算式的開頭使用（例如，`[vault(foo) | equals(bar)]` 用於檢查 `foo` 配置庫值是否等於 `bar`）。

## CSV 函式

### csv(value)

在從 CSV 檔案載入資料後使用。`csvListRecords` 操作會解析 CSV 檔案，而 CSV 格式化器會像其他格式化器一樣，透過從 CSV 文件生成值來執行。

* **value**：用於查詢值的 CSV 列標題字串。如果 CSV 檔案沒有標題，並且你將 *requireheader* 屬性設定為 false，則可以透過通用索引（c1、c2、c3、...）存取列。

#### 範例

在以下片段中，CSV 文件在 ArcScript 的記憶體中定義。

```xml theme={null}
<arc:set attr="data" value=
"column1,column2,column3
entry1,entry2,entry3
entry4,entry5,entry6"
/>
```

接下來，呼叫 `csvListRecords` 操作，並從範例 CSV 文件顯示 CSV 格式化器。

```xml theme={null}
<arc:call op="csvListRecords">
Row [_index] values: [csv('column1')], [csv('column2')], [csv('column3')]
</arc:call>
```

執行此程式碼會顯示以下輸出：

```
Row 1 values: entry1, entry2, entry3
Row 2 values: entry4, entry5, entry6
```

## JSON 函式

### hasjsonpath(jsonpath)

檢查輸入的 jsonpath 是否存在於 JSON 文件中，並傳回布林值（true/false）。

* **jsonpath**：要檢查的相對 jsonpath。

#### 範例

```xml theme={null}
<arc:set attr="json.text">
  {
    "key1": null,
    "key2": "this is a string",
    "key3": "hello world",
    "key4": 123,
    "key5": {},
    "key6": \[],
    "key7": true
  }
</arc:set>
<arc:set attr="json.jsonpath" value="/json"/>
<arc:call op="jsonDOMSearch" in="json" out="result">
  <!-- This checks to see if the desired jsonpath exists and throws an error if it does not.  -->
  <arc:if exp="[hasjsonpath(key10) | equals(false)]">
    <arc:throw code="noJSONPath" desc="The jsonpath you were looking for does not exist!" />
  </arc:if>
</arc:call>
```

### isjsonpathnull(jsonpath, \[ifTrue], \[ifFalse])

檢查輸入的 jsonpath；如果 jsonpath 為 null 或不存在，則傳回布林值（true/false）。

* **jsonpath**：要檢查的可選相對 json。
* **ifTrue**：如果格式化器解析為 true，則傳回的可選值。
* **ifFalse**：如果格式化器解析為 false，則傳回的可選值。

#### 範例

```xml theme={null}
<arc:set attr="json.text">
  {
    "key1": null,
    "key2": "this is a string",
    "key3": "hello world",
    "key4": 123,
    "key5": {},
    "key6": \[],
    "key7": true
  }
</arc:set>
<arc:set attr="json.jsonpath" value="/json"/>
<arc:call op="jsonDOMSearch" in="json" out="result">
  <arc:if exp="[IsJSONPathNull(key1) | equals(true)]" >
    <!-- This executes because key1 has a value of null -->
    <arc:set attr="_log.info" value="The jsonpath for key1 either has a value of null or does not exist." />
    <!-- Overriding the default true/false output of the formatter to 1/0 -->
    <arc:if exp="[IsJSONPathNull(key10, 1, 0) | equals(1)]" >
      <!-- This executes because key10 does not exist within the input json text -->
      <arc:set attr="_log.info" value="The jsonpath for key10 either has a value of null or does not exist." />
    </arc:if>
  </arc:if>
</arc:call>
```

### jsonpath(jsonpath)

可以在呼叫具有可用 JSON DOM 的 JSON 操作時使用此格式化器。可以使用 [jsonDOMSearch](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/scripting/operations/op-json-dom-search.md) 和 [jsonDOMGet](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/scripting/operations/op-json-dom-get.md) 操作來解析 JSON 文件。jsonpath 格式化器是 DOM 物件的格式化器，它像其他格式化器一樣透過從 JSON 文件生成值來執行。它會傳回 JSON 文件的當前 jsonpath 位置。也可以提供相對 jsonpath 字串來查詢關聯的 JSON 值。

* **jsonpath**：用於查詢關聯 JSON 值的可選相對 jsonpath。

#### 範例

```xml theme={null}
<arc:set attr="json.text">
  {
    "key1": null,
    "key2": "this is a string",
    "key3": "hello world",
    "key4": 123,
    "key5": {},
    "key6": \[],
    "key7": true
  }
</arc:set>
<arc:set attr="json.jsonpath" value="/json"/>
<arc:call op="jsonDOMSearch" in="json" out="result">
  <!-- This prints 'I just want to say, hello world!' to the application log -->
  <arc:set attr="_log.info" value="I just want to say, [jsonpath(key3)]!"/>
</arc:call>
```

### jsonsubtree(jsonpath)

可以使用 jsonsubtree 從巢狀 JSON 結構中解析 JSON 子樹。

* **jsonpath**：可選的相對 jsonpath 字串，用於指示從結構的哪個層級開始。

#### 範例

以下指令碼在 JSON 資料的 `/json/Event/Attendees` 物件下包含三個 `User` 項目。`Attendees` 物件是根物件的子樹。

```xml theme={null}
<arc:setc attr="json.text">
{
  "Event": {
    "Subject": "Meeting",
    "Attendees": {
      "User": [
        {
          "Code": "1",
          "Name": "Jane Doe"
        },
        {
          "Code": "2",
          "Name": "John Smith"
        },
        {
          "Code": "3",
          "Name": "Alex Johnson"
        }
      ]
    }
  }
}
</arc:setc>
<arc:set attr="json.jsonpath" value="/json/Event/Attendees" />
<arc:call op="jsonDOMSearch" in="json">
<arc:set attr="_log.info">  <!-- Logging the results to the application log -->
[jsonsubtree(.)]  <!-- Insert your desired jsonpath inside the parentheses -->
</arc:set>
</arc:call>
```

在此範例中，jsonpath 是 `.` 字元，它指示指令碼根據其在根物件中的位置使用當前 jsonpath。這裡，該路徑為 `/json/Event/Attendees`，會傳回全部三個項目。

下圖顯示了它在**日誌**頁面的[應用程式日誌](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/getting-started/administration/activity.md#應用程式日誌)中的顯示方式：

![jsonsubtree result in the Activity log](https://mintcdn.com/qiao/HyyOl9gYIsxaiGgh/26.4/images/jsonsubtree_activity_log.png?fit=max\&auto=format\&n=HyyOl9gYIsxaiGgh\&q=85\&s=c9df00f1370f8b74048649cfb09fc5dd)

以下是原始 JSON 子樹結果：

```
"Attendees": {
      "User": [
        {
          "Code": "1",
          "Name": "Jane Doe"
        },
        {
          "Code": "2",
          "Name": "John Smith"
        },
        {
          "Code": "3",
          "Name": "Alex Johnson"
        }
      ]
    }
```

若要僅顯示 `/json/Event/Attendees` 中第二次出現的 `User` jsonpath 的子樹，請將 `jsonsubtree` 格式化器呼叫中的路徑替換為 `jsonsubtree(User/\[2\])`。這會產生以下輸出：

```
{
  "Code": "2",
  "Name": "John Smith"
}
```

### jsontype(jsonpath)

傳回當前 JSON 名稱-值對的資料型別（字串、數字、物件、陣列或布林值）。

* **jsonpath**：用於查詢關聯 JSON 值的可選相對 jsonpath。

#### 範例

```xml theme={null}
<arc:set attr="json.text">
  {
    "key1": null,
    "key2": "this is a string",
    "key3": "hello world",
    "key4": 123,
    "key5": {},
    "key6": \[],
    "key7": true
  }
</arc:set>
<arc:set attr="json.jsonpath" value="/json"/>
<arc:call op="jsonDOMSearch" in="json" out="result">
  <!-- Creating some output data that describes various elements of the input json -->
  <arc:set attr="output.data">The jsontype of key4 is [jsontype(key4)]
The jsontype of key5 is [jsontype(key5)]
The jsontype of key6 is [jsontype(key6)]
The jsontype of key7 is [jsontype(key7)]
  </arc:set>
</arc:call>

<arc:set attr="output.filename" value="output.txt" />
<arc:push item="output" /> 

<!-- contents of output.txt -->

The jsontype of key4 is NUMBER
The jsontype of key5 is OBJECT
The jsontype of key6 is ARRAY
The jsontype of key7 is BOOL
```

## XML 函式

### hasxpath(xpath)

檢查輸入的 xpath 是否存在於 XML 文件中，並傳回布林值（true/false）。

* **xpath**：要檢查的相對 xpath。

#### 範例

```xml theme={null}
<arc:set attr="xml.text">
  <Items>
    <Foo>Bar</Foo>
    <Bar>Foo</Bar>
  </Items>
</arc:set>
<arc:set attr="xml.xpath" value="/Items"/>
<arc:call op="xmlDOMSearch" in="xml" out="result">
  <!-- This checks to see if the desired xpath exists and throws an error if it does not  -->
  <arc:if exp="[hasxpath(helloworld) | equals(false)]">
    <arc:throw code="noXPath" desc="The xpath you were looking for does not exist!" />
  </arc:if>
</arc:call>
```

### isxpathnull(xpath, \[ifTrue], \[ifFalse])

檢查輸入的 xpath；如果 xpath 為 null 或不存在，則以 `xsi:nil` XML 屬性（`xsi:nil="true/false"`）的形式傳回布林值。使用 *ifTrue* 和 *ifFalse* 參數指定條件滿足和不滿足時的替代值。

* **xpath**：要檢查的可選相對 xpath。
* **ifTrue**：如果格式化器解析為 true，則傳回的可選值。
* **ifFalse**：如果格式化器解析為 false，則傳回的可選值。

#### 範例

```xml theme={null}
<arc:set attr="xml.text">
  <Items>
    <Foo>Bar</Foo>
    <Bar>Foo</Bar>
    <helloworld xsi:nil="true" />
  </Items>
</arc:set>
<arc:set attr="xml.xpath" value="/Items"/>
<arc:call op="xmlDOMSearch" in="xml" out="result">
  <arc:if exp="[IsXPathNull(helloworld) | contains(true)]" >
    <!-- This executes because the 'helloworld' has the xsi:nil attribute set to true -->
    <arc:set attr="_log.info" value="The xpath for 'helloworld' either has a value of null or does not exist." />
    <!-- Overriding the default output of the formatter to use true/false. If the exp is true, the script inside runs. -->
    <arc:if exp="[IsXPathNull(waldo, true, false)]" >
      <!-- This executes because the 'waldo' element does not exist within the input xml text -->
      <arc:set attr="_log.info" value="The xpath for 'waldo' either has a value of null or does not exist." />
    </arc:if>
  </arc:if>
</arc:call>
```

### xpath(xpath)

在呼叫具有可用 XML DOM 的 XML 操作時使用。可以使用 [xmlDOMSearch](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/scripting/operations/op-xml-dom-search.md) 和 [xmlDOMGet](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/scripting/operations/op-xml-dom-get.md) 操作來解析 XML 文件。XPath 格式化器是 DOM 物件的格式化器，它像其他格式化器一樣透過從 XML 文件生成值來執行。它會傳回 XML 文件的當前 XPath 位置。

* **xpath**：用於查詢關聯 XML 值的可選相對 XPath 字串。

#### 範例

在以下片段中，XML 文件在 ArcScript 的記憶體中定義。

```xml theme={null}
<arc:set attr="text">
  <root>
    <A>Value_One</A>
    <A>
      <B>
        <C>Value_Two</C>
      </B>
    </A>
    <A>
      <B>Value_Three</B>
    </A>
  </root>
</arc:set>
```

在此片段中，呼叫 [xmlDOMSearch](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/scripting/operations/op-xml-dom-search.md) 操作，並從範例 XML 文件顯示 XPath 格式化器。

```xml theme={null}
<arc:call op="xmlDOMSearch?xpath=/root/A">
  Current XPath is [xpath] and the 'B' element value is [xpath(B) | empty("not present")]
</arc:call>
```

針對前面的 XML 文件執行時，此程式碼會顯示以下輸出。

```
Current XPath is /root/A[1] and the 'B' element value is not present
Current XPath is /root/A[2] and the 'B' element value is not present
Current XPath is /root/A[3] and the 'B' element value is Value_Three
```

XPath 格式化器會顯示迭代的三個 `A` 元素，但只顯示最終 `B` 元素中的 `Value_Three`，因為 `[xpath(B)]` 會忽略其他元素中的值。

### xpathcount(xpath)

類似於 XPath 格式化器，但它傳回與所提供 XPath 匹配的元素的*計數*。在呼叫具有可用 XML DOM 的 XML 操作時使用。可以使用 [xmlDOMSearch](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/scripting/operations/op-xml-dom-search.md) 和 [xmlDOMGet](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/scripting/operations/op-xml-dom-get.md) 操作來解析 XML 文件。XPathCount 格式化器是 DOM 物件的格式化器，它像其他格式化器一樣透過從 XML 文件生成計數來執行。

* **xpath**：用於計算計數的可選相對 XPath 字串。

#### 範例

```xml theme={null}
<arc:set attr="xml.xpath" value="/Items/Cars/Subaru" />
<arc:set attr="xml.text">
 <Items>
  <Cars>
    <Subaru>
      <Color>Blue</Color>
      <Year>2017</Year>
    </Subaru>
    <Honda>
      <Color>Red</Color>
    </Honda>
  </Cars>
</Items>
</arc:set>
<arc:call op="xmlDOMSearch" in="xml" out="result">
  <!-- xpathcount is a context-sensitive function in arcscript. If an xml document is loaded in a 
       search, xpathcount returns the count of the number of elements that match the provided xpath. -->
  <arc:set attr="output.Data" value="[xpathcount('/Items/Cars/*/Color')]" />
</arc:call>

<arc:set attr="output.filename" value="test.txt" />
<arc:push item="output" />
```

執行此程式碼時，它會傳回 `2` 作為輸出。

### xsubtree(xpath)

從巢狀 XML 結構中解析 XML 樹。

* **xpath**：可選的相對 XPath 字串，用於指示從結構的哪個層級開始。

#### 範例

在下面的範例 XML 文件中，`/Event/Attendees` 下有三個項目。

```xml theme={null}
<arc:set attr="xml.text">
<Event>
    <Subject>Meeting</Subject>
    <Attendees>
        <User>
            <Code>1</Code>
            <Name>TEST1</Name>
        </User>
        <User>
            <Code>2</Code>
            <Name>TEST2</Name>
        </User>
        <User>
            <Code>3</Code>
            <Name>TEST3</Name>
        </User>
    </Attendees>
</Event>
</arc:set>

<arc:set attr="xml.xpath" value="/Event/Attendees" />
<arc:call op="xmlDOMSearch" in="xml">
  [xsubtree(.)]  <!-- Insert desired xpath in parentheses  -->
</arc:call>
```

`xsubtree` 命令中的 `.` 字元指示指令碼使用當前 xpath。在此範例中，該路徑為 `/Event/Attendees`，會傳回全部三個項目：

```xml theme={null}
<User>
  <Code>1</Code>
  <Name>TEST1</Name>
</User>
<User>
  <Code>2</Code>
  <Name>TEST2</Name>
</User>
<User>
  <Code>3</Code>
  <Name>TEST3</Name>
</User>
```

若要僅顯示 `/Event/Attendees` xpath 中第二次出現的 `User` 子樹，請將命令替換為 `xsubtree(User[2])`。其結果為：

```xml theme={null}
<User>
  <Code>2</Code>
  <Name>TEST2</Name>
</User>
```

## 其他函式

### guid(includehyphens)

生成全域唯一識別碼 (GUID) 值。預設情況下，格式化器會在單個未格式化字串中傳回所有字元。要包含符合標準 8-4-4-4-12 GUID 格式的連字元，請使用 *includehyphens* 參數並將其設定為 *true*。

* **includehyphens**：設定為 *true* 可在傳回的 GUID 中包含連字元。

此格式化器不會修改輸入屬性（變數），因此不需要此類輸入屬性。

#### 範例

```xml theme={null}
<arc:set attr="myGUID" value="[guid(true)]" />
```

### vault(ItemName, \[ifnotexists], \[provider])

傳回[全域設定配置庫](https://docs.kasoftware.com/26.4/self-hosted/zh-Hant/getting-started/administration/settings/global-settings-vault.md)中與所提供 *ItemName* 值匹配的配置庫專案值。預設情況下，如果配置庫專案不存在，則會擲回錯誤。

* **ItemName**：要檢索的配置庫專案名稱。名稱僅在同一個提供者內唯一。
* **ifnotexists**：為防止配置庫專案不存在時擲回錯誤，請提供此可選參數和預設值，例如 `value does not exist`。當找不到具有指定 *ItemName* 的配置庫專案，或指定的提供者中不存在該專案時，會傳回該值。此參數不會抑制名稱衝突錯誤；如果請求確實存在歧義，無論是否提供此參數都會擲回錯誤。

  如果 *provider* 與任何已配置的提供者名稱都不匹配，該格式化器將靜默解析為空值，此時不會套用 *ifnotexists* 值。
* **provider**：要從中讀取的提供者的顯示名稱，匹配時不區分大小寫。本機配置庫的提供者名稱為 `Local`。空字串視為未提供此參數。

在多個提供者之間按名稱解析時，適用以下規則：

| 情況 | 結果 |
| - | - |
| 名稱僅存在於一個提供者中 | 正常解析 |
| 名稱同時存在於本機配置庫和某個外部提供者中 | 使用本機配置庫 |
| 名稱存在於兩個或更多外部提供者中，且本機配置庫中不存在 | 錯誤：報告名稱衝突 |

**選擇合適的寫法：**

* 如果名稱在所有提供者中唯一，請僅使用名稱（`[Vault(itemName)]`）。這是最常見的情況。
* 如果同一名稱存在於多個提供者中，或者希望在指令碼中明確指定讀取來源，請新增 *provider* 參數。

> [!NOTE]
>
> ArcScript 編輯器中的配置庫選擇器會顯示提供者欄，但插入的程式碼片段始終只包含名稱：`[Vault(ItemName)]`。如果該名稱在多個提供者中不唯一，請在插入程式碼片段後手動新增 *provider* 參數。
>
> 在指令碼上下文中引用加密配置庫專案時請務必小心，以確保日誌中不包含敏感資訊。

#### 範例

```xml theme={null}
<!-- Bare name: use when the name is unique across all providers -->
<arc:set attr="URLtoResource" value="[Vault(commonURL)]" />

<!-- With provider specified: use when the same name exists in more than one provider -->
<arc:set attr="apiKey" value="[Vault(apiKey, , AzureKV)]" />

<!-- With ifnotexists fallback -->
<arc:set attr="token" value="[Vault(apiToken, default-token)]" />

<!-- Piped into another formatter -->
<arc:set attr="token" value="[Vault(apiToken) | tolower()]" />
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.