duannao3402 2017-03-07 10:02
浏览 91
已采纳

Golang将字符串转换为单个json值而不是列表,类似于python中的json.loads

Apologies for this noob question.

I am trying to convert a string to json. The string is already in json format like

{ "system1": "Service 1", "System2": "Service2" } 

or

{ "system1": "Service 1", "device": "Service 10", "Something": "port 22" }

and so on. The number of this key-value pair is not known at compile time, and is known only at the runtime.

I am able to load it to a struct, with predefined fixed keynames, but since the number of keys are varying, I am stuck at generating a json with respect to the structure of the string.

I am not looking for pushing it to a string : []map[string]string and my aim is to generate individually generate the key-value pair similar to python's json.loads on the string (Not prefering string : []map[string]string because to get an element out of it, I have to iterate over it, which takes O(n) time, but since the keys are known in runtime, and not a list, I could directly call it as if value.Key. Please correct me if I am wrong.)

The way I could do it with python was,

>>> a =  { "system1": "Service 1", "System2": "Service2" } 
>>> b = json.loads(a)
>>> b
{u'system1': u'Service 1', u'System2': u'Service2'}

and I could access elements as

b['system1']

without iterating over b, because it is not a slice.

Any guidance is appreciated.

Thanks, Scott.

  • 写回答

1条回答 默认 最新

  • doqp87012 2017-03-07 10:24
    关注

    You can use unmarshal the string in a map[string]interface{}. For example https://play.golang.org/p/fjgg0iQgV1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题