0

I have written a javascript function to show all the inner data elements of a JSON object in an alert.

Here is my code

function allElements(moduleName) {
switch (moduleName) {
    default :
        return {
            "glossary": {
                "title": "example glossary",
                "GlossDiv": {
                    "title": "S",
                    "GlossList": {
                        "GlossEntry": {
                            "ID": "SGML",
                            "SortAs": "SGML",
                            "GlossTerm": "Standard Generalized Markup Language",
                            "Acronym": "SGML",
                            "Abbrev": "ISO 8879:1986",
                            "GlossDef": {
                                "para": "A meta-markup language,such as DocBook",
                                "GlossSeeAlso": ["GML", "XML"]
                            },
                            "GlossSee": "markup"
                        }
                    }
                }
            }
        }
}

}

function getData(data) {
    var table = ""
    for (var i in data) {
        if (i.constructor === "string".constructor) {
            table += i + " -> " + data[i]
        } else if (i.constructor === [].constructor) {
            for (j in i) {
                table += getData(i[j])
            }
        } else if (i.constructor === {}.constructor) {
            for (j in i) {
                table += getData(i[j]) 
            }
        }
    }
    return table
}

function fun() {
    alert(getData(allElements("ignored argument")))
}

above logic was here. But it shows only s1,s2,s3 and 'second object' only. The whole object is recognized only as one object. It does not go into that inner object. Can someone tell me how can I get this done.

(Edited the json object)

Community
  • 1
  • 1
bula
  • 8,719
  • 5
  • 27
  • 44
  • How are you alerting? Can you post that line? It sounds like you're just getting the object's toString output. – elclanrs Feb 27 '14 at 10:20
  • 3
    There's no JSON there. You have JavaScript literals. – Quentin Feb 27 '14 at 10:21
  • eclanrs - I have put that at the last line. Inside the fun function. Quentin - I can't get you. How can I use it as a JSON. – bula Feb 27 '14 at 10:25
  • You shouldn't use `alert` for debuggin purposes, use the console but try `alert(JSON.stringify(obj))` – elclanrs Feb 27 '14 at 10:27
  • Quentin - I have edited the question. – bula Feb 27 '14 at 10:52
  • And if it is a JSON object, why not iterate through it like this: http://stackoverflow.com/questions/1078118/how-do-i-iterate-over-a-json-structure – Asons Feb 27 '14 at 11:30

0 Answers0