davdic
davdic

Reputation: 249

Break down JSON properties to array of objects

I am trying to transform a simple JSon object into an array of objects with keys and values broken out, but I'm not sure how to quite get there.

I have tried this a number of ways but the closest I got was to create an object with two arrays, instead of an array with multiple objects with two properties each:

EDIT: I am trying to write a spec which would take any object, not this specific object. I do not know what the incoming object will be other than it will have simple properties (values will not be arrays or other objects).

Sample Input:

{
  "property": "someValue",
  "propertyName" : "anotherValue"
}

Expected Output:

{
    "split_attributes": [
        {
            "key" : "property",
            "value": "someValue"
        },
        {
            "key" : "propertyName",
            "value" : "anotherValue"
        }
    ]
}

My spec so far:

{ 
  "operation": "shift",
    "spec": {
       "*": {
        "$": "split_attributes[#0].key",
        "@": "split_attributes[#0].value"
      }
    }
  }

Produces

{
  "split_attributes" : [ 
     {
      "key" : [ "property", "propertyName" ], 
      "value" : [ "someValue", "anotherValue"]
     }
  ]
}

Upvotes: 0

Views: 191

Answers (1)

davdic
davdic

Reputation: 249

SOLUTION

I was pretty close, and after looking at the tests, the solution was obvious (it's identical to one of the tests)

{ 
  "operation": "shift",
    "spec": {
       "*": {
        "$": "split_attributes[#2].key",
        "@": "split_attributes[#2].value"
      }
    }
  }

From what it seems, I was creating an array but I was looking at the wrong level for an index to the new array. I'm still fuzzy on the whole # level (for example where in the "tree" (and of which object) is #0, #1 and #2 actually looking).

Upvotes: 1

Related Questions