Zeng Cheng
Zeng Cheng

Reputation: 825

JavaScript turn string into json object

So, I have this function that works to get a JSON object but I want to make it simplier so I created a function to get the values of the JSON object. Why doesn't it work?

var itemData = {
    weapon: function () {
        return {
            1: {
                'name': 'Dagger',
                    'extra_skill': 'none',
                    'cost': 500,
                    'attack': 5
            },
            2: {
                'name': 'Pickaxe',
                    'extra_skill': 'mining',
                    'cost': 25,
                    'attack': 5
            }
        }
    },
    getWeapon: function (value, x) {
        var obj = JSON.parse(value);
        return itemData.weapon()[x].obj
    }
}

// outputs: Dagger
console.log(itemData.weapon()[1].name)

// Get the name of weapon 1
// however, it outputs: Uncaught SyntaxError: Unexpected token a
console.log('Getting weapon... ' + itemData.getWeapon('name', 1))

What am I doing wrong?

Upvotes: 0

Views: 58

Answers (1)

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20399

You actually don't need JSON parsing at all to get this working, because there is nowhere where you have a JSON string that needs to be parsed.

Here is a working example:

var itemData = {
    weapon: function () {
        return [
            {
                'name': 'Dagger',
                    'extra_skill': 'none',
                    'cost': 500,
                    'attack': 5
            },
            {
                'name': 'Pickaxe',
                    'extra_skill': 'mining',
                    'cost': 25,
                    'attack': 5
            }
        ];
    },
    getWeapon: function (value, x) {
        return itemData.weapon()[x][value];
    }
}

// outputs: Dagger
console.log(itemData.weapon()[0].name)

// outputs: Getting weapon... Pickaxe
console.log('Getting weapon... ' + itemData.getWeapon('name', 1))

Upvotes: 5

Related Questions