2017-07-28 80 views
-1

我主要看着在golang中取消編組下面的JSON數組。嵌套的Json數組構造golang中的un-marshalling

{ 
"status":{"code":"SUCCESS"}, 
"result": { 
       "total_records":1, 
       "records": [{ 
          "last_modified_timestamp":1501209015807, 
          "dns_servers":null, 
          "is_secured":false, 
          "nis_domains":null, 
          "storage_platform_resource_key":"e1ee32f9-6576-11e7-82a8-00a098697714", 
          "name":"vs1", 
          "nis_servers":null, 
          "created_timestamp":1501208944094, 
          "dns_domains":null, 
          "key":"f59dacca-7379-11e7-82a8-00a098697714" 
         }] 
      } 
} 

我正在尋找這裏提取「關鍵」字段。試過下面的語法,但不能成功地得到我想要的。

var dat map[string]interface{} 

// Unmarshall the JSON body 
if err := json.Unmarshal(body, &dat); err != nil { 
    fmt.Println(err) 
} 
svmRecordsMap := dat["result"].(map[string]interface{})["records"] 
fmt.Printf("%+v", svmRecordsMap) 

result := (svmRecordsMap["key"].([]interface{})[0]).(map[string]interface{}) 

在這裏的任何幫助將非常感激。請注意,我沒有看到定義相應的結構並進行復制。

謝謝!

+1

你能在「不能夠擴展到順利拿到了我想」?你有什麼具體問題? – Adrian

+0

看看這個問題/答案:https://stackoverflow.com/questions/20154606/marshall-and-unmarshall-json-content-in-golang?rq=1 –

+0

[Marshall and UnMarshall JSON Content in GoLang](https://stackoverflow.com/questions/20154606/marshall-and-unmarshall-json-content-in-golang) –

回答

0

我認爲這個solution可以給你一個提示,你想要做的是從這個JSON中提取key,而不需要任何額外的type創建。

+0

謝謝!但是如果我只想要「記錄」下的第一條記錄的「關鍵」的值? – Rakshith

+0

@Rakshith而不是做'for _,l3Elem:= range l3 {...'你只需要 'var values map [string] interface {}; err:= json.Unmarshal(l3 [0],&values)' –

0

我讓你一個例子:https://play.golang.org/p/tReMMtGA2V

package main 

import (
    "encoding/json" 
    "fmt" 
) 

func main() { 

    txt := `{ 
"status":{"code":"SUCCESS"}, 
"result": { 
       "total_records":1, 
       "records": [{ 
          "last_modified_timestamp":1501209015807, 
          "dns_servers":null, 
          "is_secured":false, 
          "nis_domains":null, 
          "storage_platform_resource_key":"e1ee32f9-6576-11e7-82a8-00a098697714", 
          "name":"vs1", 
          "nis_servers":null, 
          "created_timestamp":1501208944094, 
          "dns_domains":null, 
          "key":"f59dacca-7379-11e7-82a8-00a098697714" 
         }] 
      } 
}` 

    var dat map[string]interface{} 

    if err := json.Unmarshal([]byte(txt), &dat); err != nil { 
     fmt.Println(err) 
    } 
    svmRecordsMap := dat["result"].(map[string]interface{})["records"] 
    fmt.Printf("%+v", svmRecordsMap) 

    result := (svmRecordsMap.([]interface{})[0]).(map[string]interface{}) 

    fmt.Println(result) 

} 

在您的例子要刪除「[關鍵]」當您訪問svmRecordsMap