-2

I'm a getting a string like this from database.

[{"Key":"a","Value":"4521"},{"Key":"b","Value":"7"}]

I want to get the value of the key "b" . What is the optimal way to do that in Go?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Hash934
  • 87
  • 1
  • 11

1 Answers1

3
package main

import (
    "encoding/json"
    "fmt"
    "log"
)

func main() {
    str := `[{"Key":"a","Value":"4521"},{"Key":"b","Value":"7"}]`

    // declaring out struct we will use for unmarshaling and iteration check.
    out := []struct {
        Key, Value string
    }{}

    if err := json.Unmarshal([]byte(str), &out); err != nil {
        log.Fatal(err)
    } else {
        // searching for value.
        for i := range out {
            if out[i].Key == "b" {
                fmt.Println("Found", out[i].Value)
                return
            }
        }
    }
}

This is an easy way to do that, not optimal. Optimal wound be parse string manually, byte by byte.

Oleg Butuzov
  • 4,795
  • 2
  • 24
  • 33