Search code examples
jsongomarshalling

How do I capitalize all keys in a JSON array?


I'm reading a file.json into memory. It's an array of objects, sample:

[
{"id":123123,"language":"ja-JP","location":"Osaka"}
,{"id":33332,"language":"ja-JP","location":"Tokyo"}
,{"id":31231313,"language":"ja-JP","location":"Kobe"}
]

I want to manipulate certain keys in this JSON file, so that they start with uppercase. Meaning

"language" becomes "Language" each time it's found. What I've done so far is to make a struct representing each object, as such:

type sampleStruct struct {
    ID                   int    `json:"id"`
    Language             string `json:"Language"`
    Location             string `json:"Location"`
}

Here, I define the capitalization. Meaning, id shouldn't be capitalized, but location and language should.

Rest of the code is as such:

func main() {
    if len(os.Args) < 2 {
        fmt.Println("Missing filename parameter.")
        return
    }

    translationfile, err := ioutil.ReadFile(os.Args[1])
    fileIsValid := isValidJSON(string(translationfile))

    if !fileIsValid {
        fmt.Println("Invalid JSON format for: ", os.Args[1])
        return
    }

    if err != nil {
        fmt.Println("Can't read file: ", os.Args[1])
        panic(err)
    }
}


func isValidJSON(str string) bool {
    var js json.RawMessage
    return json.Unmarshal([]byte(str), &js) == nil
}

// I'm unsure how to iterate through the JSON objects and only uppercase the objects matched in my struct here. 
func upperCaseSpecificKeys()
// ... 

Desired output, assuming the struct represents the whole data object, transform each key as desired:

[
{"id":123123,"Language":"ja-JP","Location":"Osaka"}
,{"id":33332,"Language":"ja-JP","Location":"Tokyo"}
,{"id":31231313,"Language":"ja-JP","Location":"Kobe"}
]

Solution

  • The documentation on json.Unmarshal says (with added emphasis):

    To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match

    See example here: https://play.golang.org/p/1vv8PaQUOfg