skip to Main Content

For XML files in Ballerina, if we want to access a node with a given name nested anywhere within the tree, we can access it using the following way.

// x/**/<name> - for every element e in x, retrieves every element named name in
// the descendants of e.
 xml f = x/**/<name>;
 io:println("f",f,"nn");

Is there a similar way to access a JSON object key with a given name that can be nested anywhere inside the main JSON object?

2

Answers


  1. Chosen as BEST ANSWER
    import ballerina/io;
    
    public function main() returns error? {
        json store = {
            store: {
                book: [
                    {
                        category: "reference",
                        author: "Nigel Rees",
                        title: "Sayings of the Century"
                    },
                    {
                        category: "fiction",
                        author: "Evelyn Waugh",
                        title: "Sword of Honour"
                    },
                    {
                        category: "fiction",
                        author: "Herman Melville",
                        title: "Moby Dick"
                    },
                    {
                        category: "fiction",
                        author: "J. R. R. Tolkien",
                        title: "The Lord of the Rings"
                    }
                ],
                bicycle: {
                    color: "red",
                    price: 19.95
                }
            }
        };
    
        json|error books = store?.store?.book;
        if books is error {
            return;
        }
    
        string[] titles = from json item in <json[]>books
            select check item?.title;
        io:println(titles);
    }
    

    If we take the above JSON example, we can solve the specific scenario with optional field access and a query expression.

    Please refer these as well:


  2. For XML files in Ballerina, if we want to access a node with a given name nested anywhere within the tree we can access it using the following way.

    xml f = x/**/<name>;
    io:println("f",f,"nn");
    

    In summary, the OP refers to Convenient XML navigation.

    Is there a similar way to access a JSON object key with a given name that can be nested anywhere inside the main JSON object?

    No. At least not yet.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search