moonie
moonie

Reputation: 13

retrieve value from JSON file with duplicate keys

http://chriscargile.com/dictionary/tojson/moon.js

For example, I want to retrieve all the definitions of the word "moon" here. I have tried to use jQuery

$.getJSON(url, function (json) {
    alert(json.definition)
})

This only returns me the last definition.

Upvotes: 1

Views: 80

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337666

The issue is because duplicate keys are invalid in JSON. You need to create each pos and definition property in an object which is part of an array. If you paste your JSON file in to this validator you'll see why you only get one entry back.

A correct format would be something like this:

{
    "lemma": "moon",
    "definitions": [
        {
            "pos": "n",
            "definition": "the natural satellite of the Earth",
            "samples": [
                "the average distance to the Moon is 384,400 kilometers",
                "men first stepped on the moon in 1969"
            ]
        },
        {
            "pos": "n",
            "definition": "any object resembling a moon",
            "samples": [
                "he made a moon lamp that he used as a night light",
                "the clock had a moon that showed various phases"
            ]
        }
    ]
}

You can then use $.each (or even a plain for loop if you feel like going native) to iterate over each definition and its samples.

Upvotes: 4

Related Questions