jprichardson / node-jsonfile

Easily read/write JSON files.
MIT License
1.2k stars 321 forks source link

obj.data ? How do I read specific element in json file? #55

Closed lazarusvc closed 7 years ago

lazarusvc commented 8 years ago

Okay but what if it's in the format :

{ "data": [ { "email": " ", "products": [ ], "username": " " }, { "email": " ", "products": [ { "actual_food_amount": "15", "amount": "20", "drink": "Local Drink ", "food": "Dasheen meal w/ codfish", "id": 2, "location": "Orchard Restaurant" } ] } } and I want to read "food"

manidlou commented 7 years ago

@Lazarus118, in order to get the food value, if we assume that you already know the structure of your json file, and that's something like what you posted,

{
  "data": [
    {
      "email": " ",
      "products": [],
      "username": " "
    },
    {
      "email": " ",
      "products": [
        {
          "actual_food_amount": "15",
          "amount": "20",
          "drink": "Local Drink ",
          "food": "Dasheen meal w/ codfish",
          "id": 2,
          "location": "Orchard Restaurant"
        }
      ]
    }
  ]
}

then you can do something like the following to get an array of all the food values

'use strict';
const jf = require('jsonfile')

// return an array of all the food values async
function getFood(file, cb) {
  var fvals = []
  jf.readFile(file, (err, obj) => {
    if (err) return cb(err)
    obj.data.forEach((dat) => {
      if (dat.products && Array.isArray(dat.products) && dat.products.length > 0) {
        dat.products.forEach((prod) => {
          if (prod.food && prod.food.length > 0 && fvals.indexOf(prod.food) === -1) {
            fvals.push(prod.food)
          }
        })
      }
    })
    return cb(null, fvals)
  })
}

// return an array of all the food values sync
function getFoodSync(file) {
  try {
    var fvals = []
    jf.readFileSync(file).data.forEach((dat) => {
      if (dat.products && Array.isArray(dat.products) && dat.products.length > 0) {
        dat.products.forEach((prod) => {
          if (prod.food && prod.food.length > 0 && fvals.indexOf(prod.food) === -1) {
            fvals.push(prod.food)
          }
        })
      }
    })
    return fvals
  } catch (err) {
    throw err
  }
}

then, you can use the functions simply like this,


// get food vals async
getFood('/path/to/your/json/file', (err, vals) => {
  if (err) {
    console.error(err)
  } else {
    console.dir(vals)
  }
})

// get food vals sync
try {
  console.dir(getFoodSync('/path/to/your/json/file'))
} catch (err) {
  console.error(err)
}
lazarusvc commented 7 years ago

Nice, thanks a lot... I'll try this out and let you know...

Cheers

On Sun, Nov 6, 2016 at 8:40 PM, Mawni Maghsoudlou notifications@github.com wrote:

@Lazarus118 https://github.com/Lazarus118, in order to get the food value, if we assume that you already know the structure of your json file, and that's something like what you posted,

{ "data": [ { "email": " ", "products": [], "username": " " }, { "email": " ", "products": [ { "actual_food_amount": "15", "amount": "20", "drink": "Local Drink ", "food": "Dasheen meal w/ codfish", "id": 2, "location": "Orchard Restaurant" } ] } ] }

then you can do something like the following to get an array of all the food values

'use strict';const jf = require('jsonfile') // return an array of all the food values asyncfunction getFood(file, cb) { var fvals = [] jf.readFile(file, (err, obj) => { if (err) return cb(err) obj.data.forEach((dat) => { if (dat.products && Array.isArray(dat.products) && dat.products.length > 0) { dat.products.forEach((prod) => { if (prod.food && prod.food.length > 0 && fvals.indexOf(prod.food) === -1) { fvals.push(prod.food) } }) } }) return cb(null, fvals) }) } // return an array of all the food values syncfunction getFoodSync(file) { try { var fvals = [] jf.readFileSync(file).data.forEach((dat) => { if (dat.products && Array.isArray(dat.products) && dat.products.length > 0) { dat.products.forEach((prod) => { if (prod.food && prod.food.length > 0 && fvals.indexOf(prod.food) === -1) { fvals.push(prod.food) } }) } }) return fvals } catch (err) { throw err } }

then, you can use the functions simply like this,

// get food vals asyncgetFood('/path/to/your/json/file', (err, vals) => { if (err) { console.error(err) } else { console.dir(vals) } }) // get food vals synctry { console.dir(getFoodSync('/path/to/your/json/file')) } catch (err) { console.error(err) }

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/jprichardson/node-jsonfile/issues/55#issuecomment-258724220, or mute the thread https://github.com/notifications/unsubscribe-auth/AEkQhpDzseeFxkFHqBWqTNXBxwNELjVCks5q7nOXgaJpZM4JQxM_ .

Regards,

Austin. R. Lazarus


- WORK - Founder - BudgEat.co http://budgeat.co/ - 2016 Web Developer - ICT Unit, Gov of Dominica http://establishment.gov.dm/ - 2016 Developer - Aulavara Design & Development http://www.facebook.com/aulavara - 2012/2016 Optical Lab Technician - Optical Services Ltd. http://www.facebook.com/optiserv - 2009/2016


- ORGANIZATION - DOMINICA RED CROSS - MegaV/ODK (Digital Distribution & Recording) Coordinator - 2015


- ORGANIZATION - Rotaract District 7030 - District Editor - 2012/2014 (PAST)


- ORGANIZATION - Rotaract Club of Roseau 7030 - Professional Director - 2013/2014 (PAST) Asst. Secretary/Treasurer - 2012/2013 (PAST)


- Website - Website - Link http://www.aulatech.co

jprichardson commented 7 years ago

Thanks @mawni!