Navigating through JSON with JavaScript

前端 未结 2 1108
礼貌的吻别
礼貌的吻别 2021-01-18 14:49

OK, I have been searching through this site to find anything similar or enlightening, but I am completely stuck. I am getting some valid JSON and need to parse through it to

相关标签:
2条回答
  • 2021-01-18 15:50

    If you want to find the objects "volume", "ram" and "cpu" that's simple:

    var volume = x.prices.volume;
    var ram = x.prices.server.ram;
    var cpu = x.prices.server.cpu;
    

    or you can simply use them directly:

    console.log(x.prices.volume);
    

    If you want to find the monthly prices then:

    var prices = x.prices;
    console.log('volume, monthly=', prices.volume.gb.monthly);
    console.log('cpu, monthly=', prices.server.cpu.monthly);
    console.log('ram, monthly=', prices.server.ram.monthly);
    

    Javascript objects are really simple, there are only 2 syntax for accessing them:

    // If the key you're accessing is a constant (hardcoded):
    object.key = value;
    
    // If the key you're accessing is stored in another variable:
    var k = "key";
    object[k] = value;
    
    // Alternatively:
    object["key"] = value;
    
    0 讨论(0)
  • 2021-01-18 15:54

    I'm just a bit confused, but heres an example. Save your json to an variable and just go down the tree with node names (unless don't have any).

    This should get the volume monthly

     json.prices.volume.gb.monthly 
    

    http://jsfiddle.net/PKUBA/

    0 讨论(0)
提交回复
热议问题