Skip to main content
Question

JSONTemplater and XQuery with nested for and if statements

  • November 18, 2020
  • 2 replies
  • 82 views

dms2
Contributor
Forum|alt.badge.img+11
  • Contributor
  • 48 replies

I managed to generate a new json from the original one getting the info I need but now I see there's some missing data.

Each project group has an id, lat-lon info and an array with data for every project inside the group.

I generate a new json with a feature for every project but need to also add a feature for every project group without projects in it.

This is what I have:

[
    let $doc := fme:get-json-attribute("_response_body")
    for $i in (1 to jn:size($doc))
        let $id := $doc($i)("id")
        let $lat := $doc($i)("lat")
        let $lon := $doc($i)("lng")
        let $proj := $doc($i)("projects")
        for $j in (1 to jn:size($proj))
            return  
            {|
                {"id" : $id},
                {"lat" : $lat},
                {"lon" : $lon},
                {"proj_name" : $proj($j)("name")}
            |}
]

I've tried to nest an If statement to check when $proj is empty but it throws an error.

 

 

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.

2 replies

ebygomm
Influencer
Forum|alt.badge.img+44
  • Influencer
  • 3427 replies
  • November 18, 2020

What have you tried with the if statement? Can you share an example of the json in the _response_body?


dms2
Contributor
Forum|alt.badge.img+11
  • Author
  • Contributor
  • 48 replies
  • November 18, 2020

Ok, got it!

No nesting needed. XQuery always puzzles me and it is because I always try to recreate exactly what I'd do with some other language. 

So this works :

[
    let $doc := fme:get-json-attribute("_response_body")
    for $i in (1 to jn:size($doc))
        let $id := $doc($i)("id")
        let $lat := $doc($i)("lat")
        let $lon := $doc($i)("lng")
        let $proj := $doc($i)("projects")
        let $size := jn:size($proj)
        let $n := if ($size = 0) then 0 else 1
        for $j in ($n to $size)
            return  
            {|
                {"id" : $id},
                {"lat" : $lat},
                {"lon" : $lon},
                {"proj_name" : $proj($j)("name")}
            |}
]

I've changed this:

for $j in (1 to jn:size($proj))

 To this:

let $size := jn:size($proj)
let $n := if ($size = 0) then 0 else 1
for $j in ($n to $size)