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

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.

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