Fragment Description:



Using expvar.Func.String() to 'escape' a JSON object Using json.RawMessage to 'not escape' it.
Usage of a Struct to access json values (could be easily extended to nested one).


expvarFuncJson

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:33

/* ... <== see fragment description ... */

package main

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

type Employee struct {
    FirstName string
    LastName  string
}
type Employees []*Employee

func main() {
    x := `[{"firstName":"John", "lastName":"Doe"},
   {"firstName":"Anna", "lastName":"Smith"}]`
    // sign: type Func func() interface{}
    // Func implements Var by calling the function and formatting the returned
    // value using JSON.
    f := expvar.Func(func() interface{} { return x })
    // String() is a method of Func, sign: func (f Func) String() string
    fmt.Printf("\"f.String()\" returns:\n\t %s\n=====\n", f.String()) //JSON value escaped
    // RawMessage is a raw encoded JSON object.
    // It implements Marshaler and Unmarshaler and can be used to delay
    // JSON decoding or precompute a JSON encoding.
    fmt.Printf("\"string(json.RawMessage(x))\" returns:\n\t %s\n=====\n",
        string(json.RawMessage(x))) // JSON value unescaped
    // Decode the json object without escaping "
    e := Employees{}
    err := json.Unmarshal([]byte(json.RawMessage(x)), &e)
    if err != nil {
        log.Print(err)
    }
    for k, v := range e {
        fmt.Printf("[%d] firstName is: %s\n", k, v.FirstName)
        fmt.Printf("[%d] lastName is: %s\n", k, v.LastName)
    }
}

/* Expected Output:
"f.String()" returns:
    "[{\"firstName\":\"John\", \"lastName\":\"Doe\"}, \n\t{\"firstName\":\"Anna\", \"lastName\":\"Smith\"}]"
=====
"string(json.RawMessage(x))" returns:
    [{"firstName":"John", "lastName":"Doe"},
   {"firstName":"Anna", "lastName":"Smith"}]
=====
[0] firstName is: John
[0] lastName is: Doe
[1] firstName is: Anna
[1] lastName is: Smith
*/



Comments