2017-06-14 71 views
-2

我得到了如下的JSON數據,並想獲得ip_address 和'5865cdc5-0f8c-481b-aaa7-4adfe6cf96ae'可以是任何字符串。解析JSON格式的數據

history': { 
    '5865cdc5-0f8c-481b-aaa7-4adfe6cf96ae': { 
     'profile': [ 
     { 
      'category': 'Linux', 
      'time_stamp': 1489120439.877187, 
      'detected_time': '2017-03-10T04:33:59Z', 
      'os': 'Linux', 
      'collector_type': 'dhcp' 
     } 
     ], 
     'ip_address': [ 
     { 
      'ip': '10.204.49.218', 
      'detected_time': '2017-03-10T04:33:59Z', 
      'hostname': 'pxe-dev', 
      'collector_type': 'dhcp', 
      'time_stamp': 1489120439.875652 
     } 
     ] 
    } 
    } 

我想要'ip_address'數組。 任何幫助,請

+1

如果它保證有在歷史一個鍵 - 'Object.values(O)[0] .ip_address' – zerkms

+0

本文提供的示例不是有效的JSON。 – maddockst

+0

@ zerkms-dunno如果在2017年推薦ECMAScript 2018功能是個不錯的主意。 – RobG

回答

2

不是JSON,但正常的「半」對象,而不是 使用

//and dont use *history* var as it conflicted with global variable 
    obj = { 
    '5865cdc5-0f8c-481b-aaa7-4adfe6cf96ae': { 
     'profile': [ 
     { 
      'category': 'Linux', 
      'time_stamp': 1489120439.877187, 
      'detected_time': '2017-03-10T04:33:59Z', 
      'os': 'Linux', 
      'collector_type': 'dhcp' 
     } 
     ], 
     'ip_address': [ 
     { 
      'ip': '10.204.49.218', 
      'detected_time': '2017-03-10T04:33:59Z', 
      'hostname': 'pxe-dev', 
      'collector_type': 'dhcp', 
      'time_stamp': 1489120439.875652 
     } 
     ] 
    } 
    } 

var ip = obj['5865cdc5-0f8c-481b-aaa7-4adfe6cf96ae']['ip_address'][0]['ip']) 

var ipAddress = obj['5865cdc5-0f8c-481b-aaa7-4adfe6cf96ae']['ip_address']) 
如果要檢查JSON

,請查看以下內容,獲取前谷歌你需要解析它回到Javascript對象

obj = { 
 
    '5865cdc5-0f8c-481b-aaa7-4adfe6cf96ae': { 
 
     'profile': [ 
 
     { 
 
      'category': 'Linux', 
 
      'time_stamp': 1489120439.877187, 
 
      'detected_time': '2017-03-10T04:33:59Z', 
 
      'os': 'Linux', 
 
      'collector_type': 'dhcp' 
 
     } 
 
     ], 
 
     'ip_address': [ 
 
     { 
 
      'ip': '10.204.49.218', 
 
      'detected_time': '2017-03-10T04:33:59Z', 
 
      'hostname': 'pxe-dev', 
 
      'collector_type': 'dhcp', 
 
      'time_stamp': 1489120439.875652 
 
     } 
 
     ] 
 
    } 
 
    } 
 

 
var t = JSON.stringify(obj) 
 
var t2 = JSON.parse(t) 
 
console.log('json:', t) 
 
console.log('javascript object', t2)

+0

同意@RobG, 更新 – RizkiDPrast

+0

的obj [ '5865cdc5-0f8c-481B-aaa7-4adfe6cf96ae'] ['IP_ADDRESS '])不會是通用的,因爲5865cdc5-0f8c-481b-aaa7-4adfe6cf96ae可以是任何數字 – Kim

+0

肯定kim,對於這種情況下,你可以遍歷JavaScript對象 – RizkiDPrast