2017-06-14 92 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