DEV Community

HM
HM

Posted on

Replace json values using a mapping json

Problem statement

Given an input JSON like this

{
    "results": [
      {
        "id": 1,
        "relationx_id": "11"
      },
      {
        "id": 2,
        "relationx_id": "22"
      }
    ],
    "lookup_key": "relationx_id"
}
Enter fullscreen mode Exit fullscreen mode

and a mapping JSON like this

{
    "11": "88",
    "22": "99"
}
Enter fullscreen mode Exit fullscreen mode

Use the lookup_key to replace the value of the key as per the mapping JSON. The result should look like this

{
 "lookup_key": "relationx_id",
 "results": [
  {
   "id": 1,
   "relationx_id": "88"
  },
  {
   "id": 2,
   "relationx_id": "99"
  }
 ]
}
Enter fullscreen mode Exit fullscreen mode

Solution

package main

import (
    "encoding/json"
    "fmt"
)

var inp string = `{
    "results": [
      {
        "id": 1,
        "relationx_id": "11"
      },
      {
        "id": 2,
        "relationx_id": "22"
      }
    ],
    "lookup_key": "relationx_id"
  }`

var mapping string = `{
    "11": "88",
    "22": "99"
}`

func main() {
    var inpJ map[string]interface{}
    json.Unmarshal([]byte(inp), &inpJ)
    // fmt.Printf("%+v\n", inpJ)

    var mappingJ map[string]string
    json.Unmarshal([]byte(mapping), &mappingJ)
    // fmt.Printf("%+v\n", mappingJ)

    lookupKey := inpJ["lookup_key"].(string)
    // fmt.Printf("%+v\n", lookupKey)

    for _, result := range inpJ["results"].([]interface{}) {
        resultMap := result.(map[string]interface{})
        for k, v := range resultMap {
            if k == lookupKey {
                resultMap[k] = mappingJ[v.(string)]
            }
        }
    }
    // fmt.Printf("%+v\n", inpJ)
    b, _ := json.MarshalIndent(inpJ, "", " ")
    fmt.Println(string(b))

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)