Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunitySubmit a ticketLog In
GitHubNuGetDev CommunitySubmit a ticket

OptimizelyJSON for the Go SDK

Describes the OptimizelyJSON object that the Optimizely Feature Experimentation Go SDK uses to retrieve JSON.

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:

MethodParametersDescription
ToStringnoneReturns a string representation of the JSON object
ToMapnoneReturns a map representation of the JSON object: (map[string]interface{})
GetValuejsonKey string, sObj interface{}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".

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 easily 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