Dynamical Nested JSON Objects by Golang

This sample script dynamically creates nested JSON objects.

Script

obj := map[string]interface{}{}
for i := 1; i <= 5; i++ {
    value := map[string]interface{}{
        fmt.Sprintf("B_key%d", i): map[string]interface{}{
            "C_key": "value",
        },
    }
    obj[fmt.Sprintf("A_key%d", i)] = value
}

Result

{
  "A_key1": {
    "B_key1": {
      "C_key": "value"
    }
  },
  "A_key2": {
    "B_key2": {
      "C_key": "value"
    }
  },
  "A_key3": {
    "B_key3": {
      "C_key": "value"
    }
  },
  "A_key4": {
    "B_key4": {
      "C_key": "value"
    }
  },
  "A_key5": {
    "B_key5": {
      "C_key": "value"
    }
  }
}

 Share!