/ deform

Golang: simple map operations

Hi there, today we'd like to introduce you a package which will help you to deal some maps in a json path way.

Let's assume you have a response from some service:

var document map[string]interface{}
err := json.Unmarshal(someCrazyResponse, &document)
fmt.Println(document)

and your document map is

map[string]interface{}{
	"one": []map[string]interface{}{
		{
			"two": []map[string]interface{}{
				{"three": "got three"},
				{"four": "got four"},
			},
		},
		{
			"two": []map[string]interface{}{
				{"five": "got five"},
				{"six": "got six"},
			},
		},
		{
			"two": []map[string]interface{}{
				{"seven": "got seven"},
				{"eight": "got eight"},
			},
		},
		{
			"three": []map[string]interface{}{
				{"four": map[string]interface{}{
					"five": "six",
				}},
				{"seven": map[string]interface{}{
					"eight": "ten",
				}},
			},
		},
	},
}

You need to extract a property located in one[2].two[1].eight which is currently ten

In golang it's a quite long string:

myVar := document["one"].([]map[string]interface{})[2]["two"].([]map[string]interface{})[1]["eight"]

It also can panic because in some of these documents there is no such property one[3].two

The package

So, we have developed a go-json-map package.

Using it you can:

  • get a property

      myVar, err := GetProperty(document, "one[2].two[1].eight")
    
  • create some property which does not exist in a document

      err := CreateProperty(document, "path.which.does.not.exist", "some value")
    
      err := CreateProperty(document, "path/which/does/not/exist/separated/using/slashes/", "some value", "/")
    
  • update missing or existing property

      err := UpdateProperty(document, "path.which.should.be.updated", "some value")
    
      err := UpdateProperty(document, "path/which/does/not/exist/separated/using/slashes/", "some value", "/")
    
      err := UpdateProperty(document, "one[2].two[1].eight",  "eleven")
      
      err := UpdateProperty(document, "one[3].three[2].four", []int{1,2,3,4})
    
  • delete a property

      err := DeleteProperty(document, "one[3].three[1].seven.eight")
    

Conclusion

This package allows you to work with maps a bit easier :D