agustin agustin - 1 year ago 53
JSON Question

R - Create JSON for Adobe Analytics API call - define object conditionally

I have following code to create a JSON for making a call to Adobe Analytics API (method segment.save)

item <-
list(definition = list(
container = list (
type = "hits",
operator = "or",
rules=I(list(
list(value= "test1 test2",
operator = "contains_any",
element = "page")))

)
),
owner="test",
reportSuiteID="test",
description="API Generated Segment",
name="test segment"
)


Once prettyfied and auto-unboxed, the result is:

> jsonlite::toJSON(item, pretty = T, auto_unbox= T)
{
"definition": {
"container": {
"type": "hits",
"operator": "or",
"rules": [
{
"value": "test1 test2",
"operator": "contains_any",
"element": "page"
}
]
}
},
"owner": "test",
"reportSuiteID": "test",
"description": "API Generated Segment",
"name": "test segment"
}


Good for creating new segments, but not so good for editing them

The JSON structure is valid, as I am able to create the new segment. However, I would like to check if the segment already exists (using f.i. the GetSegments() function from randyzwitch RSiteCatalyst package and check if name coincides already with a created segment). If the segment already exists, I want to pass the id to the API call, which is the method used for editing already existing segments. It should then look like:

> jsonlite::toJSON(item, pretty = T, auto_unbox= T)
{
"definition": {
...
},
"owner": "test",
"reportSuiteID": "test",
"description": "API Generated Segment",
"name": "test segment",
"id": "s1982XXXXXXXXX_XXXXX_XXXXX",
}


It is possible to make an if alike statement within the list() definition provided in the first piece of code? I would like to reach a solution that does not need an if statement that checks if segmentID exists and, depending on it, generates a call with id or a call without id.

Answer Source

Once a "JSON alike structure" is created using list function:

 item <- 
      list(definition = list(
        container = list (
          type = "hits",
          operator = "or",
          rules=I(list(
            list(value= "test1 test2",
                 operator = "contains_any",
                 element = "page")))

        )
      ),
      owner="test",
      reportSuiteID="test",
      description="API Generated Segment",
      name="test segment"
      )

We can push new elements to this list using the needed conditions. For example, if we have our segment IDs in a dataframe with name segments, we can push this ID to item this way:

if (!is.na(segments$segmentID[i])) {
  item <- c(item, id=segments$segmentID[i])
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download