-2

I'm looking for the simplest way to loop throug a JSON file.

The Data Syntax (can't change that):

{"1":{"name":FOO","price":"1","sold":"100"},"2":{"name":"FOO","price":"1","sold":"100"}

The data is stored i a file called prices.json. How can I loop through all 7573 entrys?

Thanks..

Bennet G.
  • 537
  • 8
  • 14
  • 1
    Possible duplicate of [Javascript iterate object](http://stackoverflow.com/questions/14379274/javascript-iterate-object) – Thilo Oct 04 '16 at 23:43

1 Answers1

1

You could simply require the json file then iterate over the properties of the object that it contains.

var prices = require('./prices.json');
for (var i in prices) {
    if (prices.hasOwnProperty(i)) {
        console.log(prices[i]); // do something with each item...
    }
}
Fraser
  • 15,275
  • 8
  • 53
  • 104
  • Error: Cannot find module 'prices.json' ? My misstake? – Bennet G. Oct 05 '16 at 00:13
  • Yes, the path must be correct - this presumes "prices.json" is in the same directory as the file the code is in. The path you enter is relative to the current document, so if your "prices.json" was in a "data" folder then you would do `var prices = require('./data/prices.json');` – Fraser Oct 05 '16 at 00:29
  • see my edit, just include `./` before the name, so you have `var prices = require('./prices.json');` – Fraser Oct 05 '16 at 00:40
  • Okay, now i'm just getting the numbers.. [1,2,3...]. But how can I access the data inside the numbers? sounds weird.. – Bennet G. Oct 05 '16 at 00:57
  • Gees - you should really go and read a book on the basics! - try `console.log(prices[item]);` – Fraser Oct 05 '16 at 01:27