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