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

huangapple go评论94阅读模式
英文:

Golang converting string to individual json values and not a list, similar to json.loads in python

问题

抱歉,我只能为您提供翻译服务,无法执行代码或返回翻译后的代码。以下是您提供的内容的翻译:

对于这个初学者问题我感到抱歉。

我正在尝试将一个字符串转换为JSON。该字符串已经是JSON格式的,例如:

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

或者

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

等等。这些键值对的数量在编译时是未知的,只有在运行时才知道。

我能够将其加载到一个结构体中,使用预定义的固定键名,但由于键的数量是变化的,我在生成与字符串结构相对应的JSON时遇到了困难。

我不想将其推送到 string : []map[string]string,我的目标是像Python的 json.loads 一样单独生成键值对(不喜欢 string : []map[string]string,因为要从中获取一个元素,我必须迭代它,这需要 O(n) 的时间,但由于键在运行时是已知的,而不是一个列表,我可以直接调用它,如 if value.Key。如果我理解错了,请纠正我。)

我在Python中可以这样做:

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

我可以像这样访问元素:

b['system1']

而无需迭代b,因为它不是一个切片。

感谢您的指导。

谢谢,
Scott.

英文:

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

得分: 2

你可以使用unmarshal将字符串解析为map[string]interface{}类型。
例如,https://play.golang.org/p/fjgg0iQgV1 中的示例代码。

英文:

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

huangapple
  • 本文由 发表于 2017年3月7日 18:02:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/42645231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定