0

So I am trying to make a quote system for a chat bot, and I'm having trouble with storing them. I have decided to move away from using a database because of how small scale it is, but I want to be able to constantly add to the file, is there any way I am able to find how many "variables" already in the file? My current file would be setup like this:

{ 
 "quote1":"texthere",
 "quote2":"texthere",
 "quote3":"texthere",
 "quote4":"texthere"
}

Is there a possible way I am able to figure out how many quotes there are in the file? I am programming in javascript.

Vinnie Leone
  • 3
  • 1
  • 2
  • 1
    Try storing them in an array [ "texthere", "texthere", "texthere", "texthere" ] and work out how to count the values in there. And [take the tour](https://stackoverflow.com/tour). – wazz Mar 18 '18 at 01:18
  • This will explain your answer completely... https://stackoverflow.com/questions/9640190/how-to-count-json-objects – Allan F. Gagnon Mar 18 '18 at 01:29

2 Answers2

2

Assuming you're reading a file, i.e: file.json and the string is stored into a variable.

You can parse, get the keys as an array and use the attribute length.

var fileStr = '{  "quote1":"texthere", "quote2":"texthere", "quote3":"texthere", "quote4":"texthere"}';

var length = Object.keys(JSON.parse(fileStr)).length;

console.log(length);
Ele
  • 33,468
  • 7
  • 37
  • 75
2

There are a couple of ways you can do this (best with Object.keys), but generally you might have more success using an array of objects. I'll go ahead and show two options:

const yourJson = require('./path/to/your/json')
const length = Object.keys(yourJson).length

Or, using an array of objects:

{
  quotes: [
    { id: 1, text: 'this is a quote' },
    { id: 2, text: 'this is a quote' }
  ]
}

And then you can grab the length of your quotes array like any other array.

jasonetco
  • 346
  • 1
  • 4
  • 11