doc.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Package objx provides utilities for dealing with maps, slices, JSON and other data.
  3. # Overview
  4. Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes
  5. a powerful `Get` method (among others) that allows you to easily and quickly get
  6. access to data within the map, without having to worry too much about type assertions,
  7. missing data, default values etc.
  8. # Pattern
  9. Objx uses a predictable pattern to make access data from within `map[string]interface{}` easy.
  10. Call one of the `objx.` functions to create your `objx.Map` to get going:
  11. m, err := objx.FromJSON(json)
  12. NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong,
  13. the rest will be optimistic and try to figure things out without panicking.
  14. Use `Get` to access the value you're interested in. You can use dot and array
  15. notation too:
  16. m.Get("places[0].latlng")
  17. Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type.
  18. if m.Get("code").IsStr() { // Your code... }
  19. Or you can just assume the type, and use one of the strong type methods to extract the real value:
  20. m.Get("code").Int()
  21. If there's no value there (or if it's the wrong type) then a default value will be returned,
  22. or you can be explicit about the default value.
  23. Get("code").Int(-1)
  24. If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating,
  25. manipulating and selecting that data. You can find out more by exploring the index below.
  26. # Reading data
  27. A simple example of how to use Objx:
  28. // Use MustFromJSON to make an objx.Map from some JSON
  29. m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)
  30. // Get the details
  31. name := m.Get("name").Str()
  32. age := m.Get("age").Int()
  33. // Get their nickname (or use their name if they don't have one)
  34. nickname := m.Get("nickname").Str(name)
  35. # Ranging
  36. Since `objx.Map` is a `map[string]interface{}` you can treat it as such.
  37. For example, to `range` the data, do what you would expect:
  38. m := objx.MustFromJSON(json)
  39. for key, value := range m {
  40. // Your code...
  41. }
  42. */
  43. package objx