我對JavaScript相當陌生,我的情況是這樣的: 我使用Google Charts來可視化一些數據,並且數據包含在Elasticsearch中。將JSON文檔轉換爲Google Chart格式
我使用Ajax命令查詢數據,但返回的數據在Google Charts中無法使用其當前格式。
這樣的查詢返回的數據:
{ took: 5 timed_out: false _shards: { total: 5 successful: 5 failed: 0 } hits: { total: 11 max_score: 1 hits: [ { _index: inventory _type: on_hand _id: 4 _score: 1 _source: { warehouse_id: 107 date: 03-28-2013 lane: M01 routes: 383 } }
我需要把它格式化像這樣谷歌圖表:
{
"cols": [
{"id":"","label":"Lane","type":"string"},
{"id":"","label":"Routes","type":"number"}
],
"rows": [
{"c":[{"v":"M01"},{"v":4657}]},
{"c":[{"v":"M02"},{"v":4419}]},
{"c":[{"v":"M03"},{"v":4611}]},
{"c":[{"v":"M04"},{"v":4326}]},
{"c":[{"v":"M05"},{"v":4337}]},
{"c":[{"v":"M06"},{"v":5363}]}
]
}
雖然我不指望有人寫代碼對於我來說,如果有人能夠爲我提供一個很好的起點來提取所需的數據,並添加適當的格式,例如"cols": [...
和"rows":[...
等,我將不勝感激。謝謝!
編輯:
我是能夠運行最新的查詢它返回一個有效的JSON格式的結果:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 7,
"max_score" : 1.0,
"hits" : [ {
"_index" : "wcs",
"_type" : "routes",
"_id" : "4",
"_score" : 1.0, "_source" : {"lane":"M04","routes":"102"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "5",
"_score" : 1.0, "_source" : {"lane":"M03","routes":"143"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "1",
"_score" : 1.0, "_source" : {"lane":"M07","routes":"80"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "6",
"_score" : 1.0, "_source" : {"lane":"M02","routes":"157"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "2",
"_score" : 1.0, "_source" : {"lane":"M06","routes":"101"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "7",
"_score" : 1.0, "_source" : {"lane":"M01","routes":"105"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "3",
"_score" : 1.0, "_source" : {"lane":"M05","routes":"160"}
} ]
}
}
但是實際需要的JSON文件必須完全按照我展示在我的谷歌圖表原來的職位能夠使用它。需要從返回的數據中提取"lane"
和"routes"
值(如上所示),並將其格式化爲原始帖子中的JSON文檔。再次感謝你。
看來,他們是兩個不同的對象定義乾脆:屬性名稱甚至不相同。你應該如何推斷這些屬性? – frenchie 2013-04-07 20:34:53
你不能讓服務器用適當的JSON響應嗎?你說你得到的格式不是很友善。 – bfavaretto 2013-04-07 20:41:42
查詢結果仍然不是有效的JSON。儘管接近。 [這是一個要點](https://gist.github.com/dinjas/d33f89982a326f76235a),修復了JSON。 [這是一個JSON驗證器](http://zaach.github.io/jsonlint/),您可以使用它來確保JSON有效並對其進行格式化。 – dinjas 2013-04-08 22:21:21