drt3751 2015-05-27 20:31
浏览 27

开始-即时修改JSON

Considering the following input:

"object": {
  "array": [
    {
      "element_field_1": some_value_1,
      "element_field_2": some_value_1,
      ... // More unknown fields
    },
    ...
  ],
  "object_field": foo,
  ... // Some more unknown fields
}

I need to iterate over every element of the array, modify fields 1 and 2 and then output the JSON object. Here's what I have for now, but it is far from being valid Go code:

func handler(w http.ResponseWriter, r *http.Request) {
    // Transform the request's body to an interface
    j := getDecodedJSON(r)

    // Iterate over every element of the array
    for i := 0; i < len(j["object"]["array"]); i++ {
        rewrite(j["object"]["array"][i])
    }

    // Encoding back to JSON shouldn't be a problem
}

func getDecodedJSON(r *http.Request) map[string]interface{} {
    dec := json.NewDecoder(r.Body)
    var j map[string]interface{}
    if err := dec.Decode(&j); err != nil {
        log.Fatal(err)
    }
    return j
}

func rewrite(element *map[string]interface{}) {
    element["element_field_1"], element["element_field_2"] = lookupValues(element)
}

Basically the error is:

invalid operation: j["object"]["array"] \
(type interface {} does not support indexing)

but of course there's a more conceptual mistake on my approach.

Writing a struct that details the content of the input isn't really an option, since I don't know the JSON keys beforehand.

How can I do this "the Go way"?

EDIT: This is the actual use case:

  • I have two web services that need a "translator" between them.
  • Service 1 makes a request to the translator, where a couple of fields are modified, everything else is left intact.
  • Then the translator takes the modified JSON and replicates the request to service 2.

In other words, this translator acts like a man in the middle for both services. Go seems to be a good option for this given its fast startup times and fast JSON handling.

I don't think it makes sense to detail every JSON field in a Go struct, since I only need to change a few fields. I'm willing to make a tradeoff in efficiency because of reflection (parsing to a map[string]interface{} should be slower than using a full-blown struct), in exchange of making the code more generic to variations of the JSON input.

  • 写回答

1条回答 默认 最新

  • doufunuo4787 2015-05-29 01:16
    关注

    Change

    j["object"]["array"][i]
    

    to

    j["object"].(map[string]interface{})["array"].([]interface{})[i]
    
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法