2016-11-28 74 views
0

知道結構在一個JSON文件中的值我有具有象下面編輯而不Golang

{ 
    "id": "0001", 
    "type": "donut", 
    "name": "Cake", 
    "ppu": 0.55, 
    "batters": { 
     "batter": [{ 
      "id": "1001", 
      "type": "Regular" 
     }, { 
      "id": "1002", 
      "type": "Chocolate" 
     }] 
    }, 
    "topping": [{ 
     "id": "5001", 
     "type": "None" 
    }, { 
     "id": "5002", 
     "type": "Glazed" 
    }, { 
     "id": "5005", 
     "type": "Sugar" 
    }, { 
     "id": "5007", 
     "type": "Powdered Sugar" 
    }] 
} 

我需要編輯的「id」值這是在「連擊」陣列數據的JSON文件。 假設我沒有使用ant struct類型來取消編組。編輯完成後,我需要再次將更新的JSON字符串寫回文件。

+0

這將是一個更清潔使用結構。事情是,你必須做'root.batters.batter [item] .id'來獲取值,如果你使用'map [string],你必須在每個間接層做一個類型斷言。接口{}'這實際上只是一些不必要的複雜問題的難看代碼。 – evanmcdonnal

+0

你爲什麼要避免一個結構?你的數據是否任意?如果是這樣,你怎麼知道你想編輯的元素? –

+0

使用'struct'會使處理更容易。有一件事可以更容易地定義結構本身,您可以將所有其他字段的類型設置爲'interface {}',並且只設置'batters map [string] [] map [string] string' – KBN

回答

0

你可以在沒有結構的情況下做到這一點,但這意味着要在整個地方使用強制轉換。這裏是一個working example

package main 

import (
    "encoding/json" 
    "fmt" 
) 

func main() { 
    str := "{ \"id\": \"0001\", \"type\": \"donut\", \"name\": \"Cake\", \"ppu\": 0.55, \"batters\": { " + 
       "\"batter\": [{ \"id\": \"1001\", \"type\": \"Regular\" }, { \"id\": \"1002\", \"type\": " + 
       "\"Chocolate\" }] }, \"topping\": [{ \"id\": \"5001\", \"type\": \"None\" }, { \"id\": \"5002\", " + 
       "\"type\": \"Glazed\" }, { \"id\": \"5005\", \"type\": \"Sugar\" }, { \"id\": \"5007\", \"type\": " + 
       "\"Powdered Sugar\" }] }" 

    jsonMap := make(map[string]interface{}) 
    err := json.Unmarshal([]byte(str), &jsonMap) 
    if err != nil { 
     panic(err) 
    } 

    batters := jsonMap["batters"].(map[string]interface{})["batter"] 

    for _, b := range(batters.([]interface{})) { 
     b.(map[string]interface{})["id"] = "other id" 
    } 

    str2, err := json.Marshal(jsonMap) 
    fmt.Println(string(str2)) 
} 

我認爲你最好使用一個結構。