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 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)