0

I am trying to work with a .json file and count how many times a value appears.

I have my example metadata.json file

{
  "name": "#1",
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Neon"
    },
    {
      "trait_type": "Color",
      "value": "Red"
    }
  ],
},
{
  "name": "#2",
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Neon"
    },
    {
      "trait_type": "Color",
      "value": "Red"
    }
  ],
}

I'm reading the .json file using the following code, which may not be the best way but does return the contents when I console.log. What I am having trouble with is how to return the value of a specific trait, such as 'Neon' from 'Background'. More specifically, I would like to count how many times 'Neon' appears in the .json file.

const fs = require("fs");
const path = require("path");
const isLocal = typeof process.pkg === "undefined";
const basePath = isLocal ? process.cwd() : path.dirname(process.execPath);


fs.readFile(`${basePath}/build/json/metadata.json`, 'utf8', function(err, contents) {
    if (err) {
      // we have a problem because the Error object was returned
      console.log('Error reading file')
    } else {
        // read json data
        let rawdata = fs.readFileSync(`${basePath}/build/json/metadata.json`);
        let data = JSON.parse(rawdata);
        console.log(data);
        }
    });
  • Why are you reading the file a second time in the `else` block? The file contents is already in the `contents` variable. – Barmar Sep 22 '21 at 19:50
  • What you posted isn't valid JSON. If it's an array of objects there needs to be `[]` around it. – Barmar Sep 22 '21 at 19:51
  • Just loop through the array, use a nested loop to loop through the attributes, and increment a counter when you find the desired trait. – Barmar Sep 22 '21 at 19:52
  • Yes, sorry I am still learning as I go, I tried to remove unnecessary info from the JSON file before posting and may have removed too much syntax. I will fix the duplicate file read, the code inside the else is pasted from another thread, and will attempt to loop through the attributes as you suggested. Thank you! – hustle crowe Sep 22 '21 at 21:46

0 Answers0