2016-11-28 73 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)) 
} 

我认为你最好使用一个结构。