DEV Community

HM
HM

Posted on

1 3

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay