0

I have converted the string temp to Json string using json.stringify and then oarThe output of console.log(b_json.x) is coming undefined. ? This is my boys.json file

{
    "b1":{

        "attractiveness":"10",
        "intelligence":"9",
        "budget":"500",
        "minAtt":"6",
        "committed":"false",
        "girlname":""

    },
    "b2":{

        "attractiveness":"15",
        "intelligence":"8",
        "budget":"600",
        "minAtt":"7",
        "committed":"false",
        "girlname":""

    },
    "b3":{

        "attractiveness":"13",
        "intelligence":"6",
        "budget":"900",
        "minAtt":"8",
        "committed":"false",
        "girlname":""

    },
}

This is my boys.js file-

var b_json = require('./boys.json');

function utility() {
    var arr_boys = new Array(3);;
    for (var i = 1 ; i < arr_boys.length; i++) {
        var temp = 'b'+i;
        var t = JSON.stringify(temp);
        var x = JSON.parse(t);
        console.log(b_json.x);
    }
}

utility()
  • Ever thought of using an array? – Adam Jenkins Feb 21 '17 at 18:16
  • Please, for everyone's sake, learn [how to debug JavaScript](http://stackoverflow.com/q/988363/215552). Examine each variable as you go into it. Pay attention to errors in the console. Try things and see if they work. – Heretic Monkey Feb 21 '17 at 18:17

3 Answers3

0

Your use of JSON is completely useless; you're converting a string back to itself.

You actually just want b_json['b' + i].

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

When you converted t into x using JSON.parse(t) this then turns what was is boys.json into a javascript object. However when you then check for b_json.x you are asking to get the "x" property from b_json - it most likely does not have a property called x. Try console.log(b_json) to see what is in the object.

Chris Cousins
  • 1,862
  • 8
  • 15
0

Why do you need JSON.parse or Stringify here. Can you directly try as?

function utility() {
    var arr_boys = new Array(3);;
    for (var i = 1 ; i < arr_boys.length; i++) {
        var temp = 'b'+i;
        //var t = JSON.stringify(temp);
        //var x = JSON.parse(t);
        console.log(b_json[temp]);
    }
}
Nitesh
  • 1,490
  • 1
  • 12
  • 20