0
{
    "itemType": [
        {
            "id": 1,
            "name": "Bamboo Sword",
            "image": "bamboosword.png"
            "atkModifier": "+4",
            "price": 4000
            "ele": "E"
        },
        {
            "id": 2,
            "name": "Simple Sword",
            "image": "simplesword.png"
            "atkModifier": "+8",
            "price": 8000
            "ele": "E"
        }
    ]
}

I have an Item class and I would like to parse the JSON and create the Item dynamically. Let's say this Item class accept the data in the JSON as input :

Item(id, name, image, atk, price, ele);

How do I do that?

Barmar
  • 741,623
  • 53
  • 500
  • 612
ayakashi-ya
  • 261
  • 3
  • 18
  • One generally does this manually from the JavaScript object that the JSON represents: `data = JSON.parse(jsonText); i = data.itemType[0]; item = new Item(i.id, i.name, i.image..)`. Of course you'll likely want to loop over the array and create many Items. – user2864740 Jan 15 '14 at 23:04
  • possible duplicate of [Casting plain objects to function instances ("classes") in javascript](http://stackoverflow.com/questions/11810028/casting-plain-objects-to-function-instances-classes-in-javascript) – Bergi Jan 15 '14 at 23:16
  • @user2864740 It gives me error: 'SCRIPT1014: Unhandled exception at line 64, column 9 in ms-appx://cfc6264e-a4a8-4932-a7bf-7e4cf8f0e857/js/game.js 0x800a03f6 - JavaScript runtime error: Invalid character File: game.js, Line: 64, Column: 9' at this data = JSON.parse("js/json/weapon.json"); --> error here for(var i=0; i<10; i++){ i = data.itemType[0]; item = new Item(i.id, i.name, i.image, i.price, i.type); console.log(item); } – ayakashi-ya Jan 15 '14 at 23:25
  • 1
    `JSON.parse` expects a string containing JSON, not a file path. You have to load the content of the file yourself. – Felix Kling Jan 15 '14 at 23:39
  • `$.getJSON("js/json/weapon.json", function (json) { var data = JSON.parse(json); for (var i = 0; i < 10; i++) { i = data.weapon[0]; item = new Item(i.id, i.name, i.image, i.price, i.type); console.log(item.name); } });` but i see no output in the console... oh would I need to get it like that? I read somewhere that if it's local file you using $.getJSON will not work... – ayakashi-ya Jan 15 '14 at 23:59
  • @user3200332 It likely *didn't* work. Handle the `failure` callback to see. In any case, that is a different question. – user2864740 Jan 16 '14 at 00:01
  • Hello, adding the `.error` callback shows that the function return with error. And it was because I miss some ','. When I correct it, it return with the same Invalid Character in `data = JSON.parse(json);` – ayakashi-ya Jan 16 '14 at 00:28
  • Just for the record, because of the same origin policy in web browsers, you can't load JSON locally (without a server). You need to use [JSONP](http://en.wikipedia.org/wiki/JSONP). I tried it myself, it works! – webketje Jan 16 '14 at 02:48

0 Answers0