[英]jq 1.5: Combining keys from one array with their values that are in a different array
我想獲取一個數組中的一些鍵值,並將它們與不同數組中的相應值進行匹配。 作為參考,我使用的是jq-1.5
我從quandl api獲得了一些數據,我正在提取一些股票數據。 例如,以下內容會刪除一些json數據。
數據如下,雖然我刪除了一些冗余數據;
{
"datatable": {
"data": [
["2012-05-18", 38.2318, 45.0, 38.0],
["2012-05-21", 34.03, 36.66, 33.0],
["2012-05-22", 31.0, 33.59, 30.94],
["2017-06-22", 153.4, 154.55, 152.91],
["2017-06-23", 155.07, 155.2, 152.65]
],
"columns": [{
"name": "date",
"type": "Date"
}, {
"name": "close",
"type": "BigDecimal(34,12)"
}, {
"name": "high",
"type": "BigDecimal(34,12)"
}, {
"name": "low",
"type": "BigDecimal(34,12)"
}]
},
"meta": {
"next_cursor_id": null
}
}
我希望將.datatable.columns [$ index1] .name中的“鍵”與.datatable.data [1]中的“values”匹配,依此類推每個迭代索引值。 我希望獲得如下輸出;
[
{
"date": "2012-05-18",
"close": 38.2318,
"high": 45.0,
"low": 38.0
},
{
"date": "2012-05-21",
"close": 34.03,
"high": 36.66,
"low": 33.0
},
{
"date": "2012-05-22",
"close": 31.0,
"high": 33.59,
"low": 30.94
},
{
"date": "2017-06-22",
"close": 153.4,
"high": 154.55,
"low": 152.91
},
{
"date": "2017-06-23",
"close": 155.07,
"high": 155.2,
"low": 152.65
}
]
到目前為止,我已經玩弄了計算索引的想法,但到目前為止,我的大部分解決方案都相當冗長,而且我發現自己走出jq到sed / awk等等我想象的很容易在jq。
這是一個幫助函數,使解決方案易於理解。 它將輸入數組轉換為一個對象,假設headers
是一個字符串數組,用作鍵名:
def objectify(headers):
[headers, .] | transpose | map( { (.[0]): .[1] } ) | add;
解決方案現在很簡單:
.datatable
| (.columns | map(.name)) as $headers
| .data
| map( objectify($headers) )
Python解決方案:
combine_keys.py腳本:
import sys, json
data = json.load(open(sys.argv[1], 'r'))
columns = [o['name'] for o in data['datatable']['columns']]
result = json.dumps([dict(zip(columns, i)) for i in data['datatable']['data']], indent=4)
print(result)
用法 :
python combine_keys.py input.json
輸出:
[
{
"low": 38.0,
"date": "2012-05-18",
"close": 38.2318,
"high": 45.0
},
{
"low": 33.0,
"date": "2012-05-21",
"close": 34.03,
"high": 36.66
},
{
"low": 30.94,
"date": "2012-05-22",
"close": 31.0,
"high": 33.59
},
{
"low": 152.91,
"date": "2017-06-22",
"close": 153.4,
"high": 154.55
},
{
"low": 152.65,
"date": "2017-06-23",
"close": 155.07,
"high": 155.2
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.