OptimizelyJSON for the Go SDK
4 min
Since statically typed languages lack native support for JSON, the Go SDK uses the OptimizelyJSON object to retrieve JSON in a flexible way.
Version
Go 1.3 and higher
Methods
You can access JSON representations with the following methods:
Method |
|---|
<th>
Parameters
</th>
<th>
Description
</th>
</tr>| `ToString` |
<td>
none
</td>
<td>
Returns a string representation of the JSON object
</td>
</tr>
<tr>
<td>
`ToMap`
</td>
<td>
none
</td>
<td>
Returns a map representation of the JSON object: `(map[string]interface{})`
</td>
</tr>
<tr>
<td>
`GetValue`
</td>
<td>
```
jsonKey string,
sObj interface{}
```
</td>
<td>
Populates a specified schema object (`sObj`) with the key/value pair of the JSON key you pass to this method.
If JSON key is empty, it populates your schema object with all JSON key/value pairs.
You can retrieve information for a nested member of the JSON data structure by using flattened JSON dot notation.\
For example, if you want to access the key `nestedField2` in `{field1: {nestedField2: "blah"}}`, you can call `GetValue` with the parameter `"field1.nestedField2"`.
</td>
</tr>The OptimizelyJSON object is defined as follows:
// OptimizelyJSON is an object for accessing JSON
type OptimizelyJSON struct {
ToString() string
//The underlying variable for the OptimizelyJson object is `map[string]interface{}`, which is the return value for `ToMap` method.
ToMap() map[string]interface{}
//"sObj" holds the schema that the user needs to pass by reference to unmarshal json content into it
GetValue(jsonKey string, sObj interface{}) error
}Examples
You can use OptimizelyJSON object, for example to:
- Get a JSON string by calling the ToString method, or
- Retrieve a specified schema from the OptimizelyJSON object by calling the GetValue method.
The following example shows how to use an OptimizelyJSON object to populate a schema object you declare.
//declare "sObj" to hold the schema object into which you later unmarshal OptimizelyJson content:
type schemaObj struct {
Field1 int
Field2 float64
Field3 string
Field4 struct {Field string}
}
sObj := schemaObj{}
//not shown: get an optimizelyJSON object, optlyJSON
//parse all json key/value pairs into your schema, sObj
err := optlyJSON.GetValue("", &sObj)
//or, parse the specified key/value pair with an integer value
var intValue int
err := optlyJSON.GetValue("field1", &intValue) // intValue stores integer value
//or, parse the specified key/value pair with a string value
var strValue string
err := optlyJSON.GetValue("field4.field", &strValue) // strValue stores string value