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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?