简体   繁体   English

将 json 中的逗号分隔字符串或 int 值解组到数组

[英]Unmarshal comma-separated string or int values in json to an array

I have a piece of code that collects key/value store into json.我有一段代码将键/值存储收集到 json 中。 Now key value store may contain array as a value, below is the json现在键值存储可能包含数组作为值,下面是 json

{
  "name":"abc",
  "address":"some address value",
  "phonenumber": "\"123123\",\"7897897\",\"45345345\""
}

and I want to unmarshal this to below struct我想把它解组到下面的结构

type myobj struct{
  Name string `json:"name"`
  Address string `json:"address`
  PhoneNumbers []string
}

the phonenumbers field is a comma separated list in json, and I want to unmarshal this to an array of strings, how to I go about this? phonenumbers 字段是 json 中的逗号分隔列表,我想将其解组为字符串数组,我如何 go 关于这个?

You can unmarshal it to a string and then split it.您可以将其解组为字符串,然后将其拆分。

type myobj struct{
  Name string `json:"name"`
  Address string `json:"address`
  PhoneNumberRaw string `json:"phonenumber"`

  PhoneNumbers []string `json:"-"`
}

// Unmarshal.
var o myobj
json.Unmarshal(yourData, &o)

// Remove the quotes and split the phone number string by comma.
o.PhoneNumbers = strings.Split(strings.ReplaceAll(o.PhoneNumberRaw, `"`, ""), ",")


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM