-2

Can you see why json values dont get saved:

Update: And if you would like to explain why this is downgraded as "Off topic"?

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type UsedInContext struct {
    UsedIn      string `json:"usedin"`
    ContextName string `json:"contextname"`
}

type ContextData struct {
    usedInContext []UsedInContext `json:"usedincontext"`
}

func saveData() {

    var jsonBlob = []byte(`{
        "usedincontext": 
        [
            {"usedin":"local", "contextname":"desktop"}
        ]
    }`)

    usedInContext := UsedInContext{}
    err := json.Unmarshal(jsonBlob, &usedInContext)
    if err != nil {
    }

    usedInContextJson, _ := json.Marshal(usedInContext)
    err = ioutil.WriteFile("data.json", usedInContextJson, 0644)
    fmt.Printf("%+v", usedInContext)
}

I get the following:

{"usedin":"","contextname":""}
Chris G.
  • 23,930
  • 48
  • 177
  • 302
  • 2
    Add the code for `UsedInContext` struct then we will be able to resolve the problem. – Himanshu Aug 31 '18 at 13:28
  • 2
    Can't say without showing us the definition of `UsedInContext`, but I'd guess your struct fields are unexported. – Adrian Aug 31 '18 at 13:32
  • Possible duplicate of [JSON and dealing with unexported fields](https://stackoverflow.com/questions/11126793/json-and-dealing-with-unexported-fields) – Martin Tournoij Sep 01 '18 at 14:24

1 Answers1

0

You unmarshal your document to the type UsedInContext, while it matches the schema for ContextData:

type ContextData struct {
    UsedInContext []UsedInContext `json:"usedincontext"` // exported
}

var data ContextData
json.Unmarshal(jsonBlob, &data)
fmt.Printf("%+v", data)
bereal
  • 32,519
  • 6
  • 58
  • 104