Skip to main content
Question

Count elements in json array

  • April 11, 2019
  • 6 replies
  • 573 views

jdh
Contributor
Forum|alt.badge.img+37
  • Contributor
  • 2002 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.

This post is closed to further activity.
It may be an old question, an answered question, an implemented idea, or a notification-only post.
Please check post dates before relying on any information in a question or answer.
For follow-up or related questions, please post a new question or idea.
If there is a genuine update to be made, please contact us and request that the post is reopened.

6 replies

takashi
Celebrity
  • 7843 replies
  • April 12, 2019

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


thijsknapen
Contributor
Forum|alt.badge.img+11
  • Contributor
  • 155 replies
  • December 22, 2020

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


peter_s
Contributor
Forum|alt.badge.img+4
  • Contributor
  • 19 replies
  • March 2, 2021

Yes, thanks @takashi - this saved my day!


salvaleonrp
Enthusiast
Forum|alt.badge.img+20
  • Enthusiast
  • 154 replies
  • April 1, 2021

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


takashi
Celebrity
  • 7843 replies
  • April 5, 2021

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")
    )
)

 


salvaleonrp
Enthusiast
Forum|alt.badge.img+20
  • Enthusiast
  • 154 replies
  • April 6, 2021

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.