Question

Count elements in json array

  • 11 April 2019
  • 6 replies
  • 101 views

Badge +22
  • Contributor
  • 1961 replies

I have a complicated json object that I would like to count the number of elements in one of it's child objects. Given the size and complexity of the original json, I would like to avoid flattening it and using the listElementCounter.


6 replies

Userlevel 2
Badge +17

Try using the XMLXQueryExtracter with the JSONiq extension. This may be a kind of hack, but works.

Example:

A Complex JSON Text (value of a feature attribute called "_json")

{
    "a" : 100,
    "b" : {
        "c" : [
            {"x" : 1},
            {"x" : 2},
            {"x" : 3}
        ],
        "d" : 200
    }
}

XQuery expression that returns the number of elements in the array "c".

jn:size(fme:get-json-attribute("_json")("b")("c"))

XMLXQueryExtractor Parameters

0684Q00000ArL1YQAV.png

Badge +3

Great, tnx for the info @Takashi Iijima​; Was looking for the same thing today 😃

Yes, thanks @takashi - this saved my day!

Badge +10

What if the element attribute "x" has duplicated values and I want to count unique Xs only?

Userlevel 2
Badge +17

What if the element attribute "x" has duplicated values and I want to count unique Xs only? 

Hi @Renato Salvaleon​ , if I understand your requirement correctly, this expression returns your desired result.

count(
    distinct-values(
        for $e in jn:members(fme:get-json-attribute("_json")("b")("c"))
        return $e("x")
    )
)

 

Badge +10

Hi @Renato Salvaleon​ , if I understand your requirement correctly, this expression returns your desired result.

count(
    distinct-values(
        for $e in jn:members(fme:get-json-attribute("_json")("b")("c"))
        return $e("x")
    )
)

 

Thanks @Takashi Iijima​ that got me the values I was looking for. It also saved me a good bit of process time by taking away four transformers and exposing my list attributes and exploding the features.

Reply