Write Struct to Json File using Struct Fields (not json keys)

go, json

Solution

If I understand your question correctly, all you want to do is remove the json tags from your struct definition.

So:

package main

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

type Rankings struct {
    Keyword  string 
    GetCount uint32 
    Engine   string 
    Locale   string 
    Mobile   bool   
}

func main() {
    var jsonBlob = []byte(`
        {"keyword":"hipaa compliance form", "get_count":157, "engine":"google", "locale":"en-us", "mobile":false}
    `)
    rankings := Rankings{}
    err := json.Unmarshal(jsonBlob, &rankings)
    if err != nil {
        // nozzle.printError("opening config file", err.Error())
    }

    rankingsJson, _ := json.Marshal(rankings)
    err = ioutil.WriteFile("output.json", rankingsJson, 0644)
    fmt.Printf("%+v", rankings)
}

Results in:

{Keyword:hipaa compliance form GetCount:0 Engine:google Locale:en-us Mobile:false}

And the file output is:

{"Keyword":"hipaa compliance form","GetCount":0,"Engine":"google","Locale":"    en-us","Mobile":false}

Running example at http://play.golang.org/p/dC3s37HxvZ

Note: GetCount shows 0, since it was read in as `"get_count"`. If you want to read in JSON that has `"get_count"` vs. `"GetCount"`, but output `"GetCount"` then you'll have to do some additional parsing.

See Go- Copy all common fields between structs for additional info about this particular situation.

Problem

How can I read a json file into a struct, and then Marshal it back out to a json string with the Struct fields as keys (rather than the original json keys)? (see `Desired Output to Json File` below...) Code: ``` package main import ( "encoding/json" "fmt" "io/ioutil" ) type Rankings struct { Keyword string `json:"keyword"` GetCount uint32 `json:"get_count"` Engine string `json:"engine"` Locale string `json:"locale"` Mobile bool `json:"mobile"` } func main() { var jsonBlob = []byte(` {"keyword":"hipaa compliance form", "get_count":157, "engine":"google", "locale":"en-us", "mobile":false} `) rankings := Rankings{} err := json.Unmarshal(jsonBlob, &rankings) if err != nil { // nozzle.printError("opening config file", err.Error()) } rankingsJson, _ := json.Marshal(rankings) err = ioutil.WriteFile("output.json", rankingsJson, 0644) fmt.Printf("%+v", rankings) } ``` Output on screen: ``` {Keyword:hipaa compliance form GetCount:157 Engine:google Locale:en-us Mobile:false} ``` Output to Json File: ``` {"keyword":"hipaa compliance form","get_count":157,"engine":"google","locale":"en-us","mobile":false} ``` Desired Output to Json File: ``` {"Keyword":"hipaa compliance form","GetCount":157,"Engine":"google","Locale":"en-us","Mobile":false} ```

Original source

Related problems