duanbarong4617
2018-08-17 09:37
浏览 58
已采纳

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

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"}
]
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dtoka218420 2018-08-17 11:06
    最佳回答

    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

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题