MarkLogic Get all Nested Field name of Json document using javascript

320 views Asked by At

I need a recursive function in javascript, which can return me all fieldname (Key Name) of my json document store in MarkLogic. JSON document is very dynamic and have multiple hierarchical elements. So need a function which can traverse through JSON and fetch all fieldname (Keys Name).

One option I thought was to get entire document into MaP object and run Map function to get all keys. But not sure whether MarkLogic allows to capture entire json doucment into Map and one can read fields names.

Thanks in Advance

Got the function to iterate through JSON document to pull Key Name

Sample JSON

var object = {
    aProperty: {
        aSetting1: 1,
        aSetting2: 2,
        aSetting3: 3,
        aSetting4: 4,
        aSetting5: 5
    },
    bProperty: {
        bSetting1: {
            bPropertySubSetting : true
        },
        bSetting2: "bString"
    },
    cProperty: {
        cSetting: "cString"
    }
}

Solution available at StackOverflow

Recursively looping through an object to build a property list

*

function iterate(obj, stack) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property], stack + '.' + property);
                } else {
                    console.log(property + "   " + obj[property]);
                    $('#output').append($("<div/>").text(stack + '.' + property))
                }
            }
        }
    }
iterate(object, '')*
1

There are 1 answers

0
David Ennis  -CleverLlamas.com On BEST ANSWER

This handy page may help: MarkLogic - Native JSON

The following will extract all property names

var json = fn.head(xdmp.unquote('{  foo : "bar", baz : { buz: "boo", chicken : { option1 : "soup", option2 : "salad" } } }'))

json.xpath("//*/name()");

Output: foo baz buz chicken option1 option2

If, after reviewing the samples on that page you still need assistance, I suggest updating your question with example JSON and desired output (even if it is meant to be dynamic, an example people can copy/paste and work with helps alot)