title: Go - Modify JSON on the fly
body: <p>Considering the following input:</p>
  
  <pre><code>"object": {
    "array": [
      {
        "element_field_1": some_value_1,
        "element_field_2": some_value_1,
        ... // More unknown fields
      },
      ...
    ],
    "object_field": foo,
    ... // Some more unknown fields
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><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 &lt; 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(&amp;j); err != nil {
          log.Fatal(err)
      }
      return j
  }
  
  func rewrite(element *map[string]interface{}) {
      element["element_field_1"], element["element_field_2"] = lookupValues(element)
  }
  </code></pre>
  
  <p>Basically the error is:</p>
  
  <pre><code>invalid operation: j["object"]["array"] \
  (type interface {} does not support indexing)
  </code></pre>
  
  <p>but of course there's a more conceptual mistake on my approach.</p>
  
  <p>Writing a <code>struct</code> that details the content of the input isn't really an option, since I don't know the JSON keys beforehand.</p>
  
  <p>How can I do this "the Go way"?</p>
  
  <p><strong>EDIT</strong>: This is the actual use case:</p>
  
  <ul>
  <li>I have two web services that need a "translator" between them.</li>
  <li>Service 1 makes a request to the translator, where a couple of fields are modified, everything else is left intact.</li>
  <li>Then the translator takes the modified JSON and replicates the request to service 2.</li>
  </ul>
  
  <p>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.</p>
  
  <p>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 <code>map[string]interface{}</code> should be slower than using a full-blown struct), in exchange of making the code more generic to variations of the JSON input.</p>