

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Hive JSON SerDe
<a name="hive-json-serde"></a>

Hive JSON SerDe 經常用來處理事件等 JSON 資料。這些事件以 JSON 編碼文字 (以新行分隔) 的單行字串表示。Hive JSON SerDe 不允許在 `map` 或 `struct` 索引鍵名稱中使用重複的索引鍵。

**注意**  
SerDe 預期每筆 JSON 文件都以單行文字表示，而且沒有行終止字元分隔記錄中的欄位。如果 JSON 文字是美化過的列印格式，則在建立資料表後嘗試在其中查詢時可能會收到下列錯誤訊息：HIVE\_CURSOR\_ERROR: Row is not a valid JSON Object (HIVE\_CURSOR\_ERROR：資料列不是有效的 JSON 物件) 或 HIVE\_CURSOR\_ERROR: JsonParseException: Unexpected end-of-input: expected close marker for OBJECT (HIVE\_CURSOR\_ERROR：JsonParseException：非預期的輸入結束：預期為 OBJECT 的關閉標記)。如需詳細資訊，請參閱 GitHub 上 OpenX SerDe 文件中的 [JSON 資料檔案](https://github.com/rcongiu/Hive-JSON-Serde#json-data-files)。

下列 DDL 陳述式範例使用 Hive JSON SerDe，以根據線上廣告資料範例建立資料表。在 `LOCATION` 子句中，請以您執行 Athena 所在位置的區域識別符 (例如 `s3://us-west-2.elasticmapreduce/samples/hive-ads/tables/impressions`) 來取代 `s3://amzn-s3-demo-bucket.elasticmapreduce/samples/hive-ads/tables/impressions` 中的 {{myregion}}。

```
CREATE EXTERNAL TABLE impressions (
    requestbegintime string,
    adid string,
    impressionid string,
    referrer string,
    useragent string,
    usercookie string,
    ip string,
    number string,
    processid string,
    browsercookie string,
    requestendtime string,
    timers struct
                <
                 modellookup:string, 
                 requesttime:string
                >,
    threadid string, 
    hostname string,
    sessionid string
)   
PARTITIONED BY (dt string)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 's3://amzn-s3-demo-bucket.elasticmapreduce/samples/hive-ads/tables/impressions';
```

## 使用 Hive JSON SerDe 指定時間戳記格式
<a name="hive-json-serde-timestamp-formats"></a>

若要從字串中剖析時間戳記值，您可以將 `WITH SERDEPROPERTIES` 子欄位新增至 `ROW FORMAT SERDE` 子句並使用它來指定 `timestamp.formats` 參數。在參數中，指定一個或多個時間戳記模式的逗號分隔清單，如下範例所示：

```
...
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
WITH SERDEPROPERTIES ("timestamp.formats"="yyyy-MM-dd'T'HH:mm:ss.SSS'Z',yyyy-MM-dd'T'HH:mm:ss")
...
```

如需詳細資訊，請參閱 Apache Hive 文件中[時間戳記](https://cwiki.apache.org/confluence/display/hive/languagemanual+types#LanguageManualTypes-TimestampstimestampTimestamps)。

## 載入資料表以進行查詢
<a name="hive-json-serde-loading-the-table"></a>

建立資料表後，請執行 [MSCK REPAIR TABLE](msck-repair-table.md) 以載入資料表，並讓其可從 Athena 查詢：

```
MSCK REPAIR TABLE impressions
```

## 查詢 CloudTrail 日誌
<a name="hive-json-serde-querying-cloud-trail-logs"></a>

您可以使用 Hive JSON SerDe 來查詢 CloudTrail 日誌。如需詳細資訊和範例 `CREATE TABLE` 陳述式，則請參閱 [查詢 AWS CloudTrail 日誌](cloudtrail-logs.md)。