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条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?