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 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,如何解決?