Home>
I want to achieve

I want to get the Value in the second layer of JSON from Key.
This time, there is always a Key named orange in the second layer, so I want to realize that I can get the Value corresponding to that Key.

Applicable JSON file
{
    "name": "test-json",
    "something": {
        "a": {
            "orange": "car",
            "apple": "train"
            },
        "b": {
            "orange": "airplane",
            "apple": "walk"
        }
    }
}
What I tried

I knew that I had to step on the first tier to get to the second tier, so
Get all the attributes directly under something, define the attributes in order from the top with the for statement, get the Key (Orange) from there, and try to get the Value (car, airplane) corresponding to the Key (Orange) from there I did, but the call to the name of the first layer defined without the for statement becomes invalid.

const jsonObject = JSON.parse (fs.readFileSync ('test.json','utf8'));
const a = JSON.stringify (jsonObject.something);
const b = JSON.parse (a);
const c = Object.keys (b);
console.log (c) // Displayed without problems
for (let i = 0;i<c.length;i ++) {
    var koko = c [i];
    var doko = JSON.stringify (jsonObject.koko);// The defined koko cannot be called
    var soko = JSON.parse (doko);
    var sore = Object.keys (soko)
    console.log (sore)
}
  • Answer # 1

      var doko = JSON.stringify (jsonObject.something [koko]);


    Then?

  • Answer # 2

    var data = {
      "name": "test-json",
      "something": {
        "a": {
          "orange": "car",
          "apple": "train"
          },
        "b": {
          "orange": "airplane",
          "apple": "walk",
          "test": {
            "c": {
              "d": [
                {"orange": "ship"},
                {"orange": "walk"},
                ]
              }
          }
        }
      }
    };
    const getOrange = data =>{
      var ret = [];
      Object.entries (data) .forEach (x =>{
        if (x [0] == "orange") {
          ret.push (x [1]);
        } else if (x [1] instanceof Object) {
          ret = ret.concat (getOrange (x [1]));
        }
      });
      return ret;
    };
    console.log (getOrange (data));