如何大写JSON数组中的所有键?

cbl*_*bll 2 json marshalling go

我正在读书file.json.它是一个对象数组,示例:

[
{"id":123123,"language":"ja-JP","location":"Osaka"}
,{"id":33332,"language":"ja-JP","location":"Tokyo"}
,{"id":31231313,"language":"ja-JP","location":"Kobe"}
]
Run Code Online (Sandbox Code Playgroud)

我想操纵这个JSON文件中的某些键,以便它们以大写字母开头.含义

"language"成为"Language"每一个它的发现时间.到目前为止我所做的是创建一个表示每个对象的结构,如下所示:

type sampleStruct struct {
    ID                   int    `json:"id"`
    Language             string `json:"Language"`
    Location             string `json:"Location"`
}
Run Code Online (Sandbox Code Playgroud)

在这里,我定义了大写.意思是,id不应该大写,但locationlanguage应.

其余的代码是这样的:

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()
// ... 
Run Code Online (Sandbox Code Playgroud)

期望的输出,假设struct表示整个数据对象,根据需要转换每个键:

[
{"id":123123,"Language":"ja-JP","Location":"Osaka"}
,{"id":33332,"Language":"ja-JP","Location":"Tokyo"}
,{"id":31231313,"Language":"ja-JP","Location":"Kobe"}
]
Run Code Online (Sandbox Code Playgroud)

mko*_*iva 6

关于json.Unmarshal说的文件(更加强调):

要将JSON解组为结构,Unmarshal将传入的对象键与Marshal使用的键(结构字段名称或其标记)匹配,更喜欢精确匹配,但也接受不区分大小写的匹配

请参见此处的示例:https://play.golang.org/p/1vv8PaQUOfg