我試圖從http調用解析json。對於我寫的HTTP調用,我很喜歡this解析json與驗證
[ //list of streams
{
"entry": "stream",
"value": {
"name": "euro", //stream name
"urls": [ //list of sources
{
"value": "tshttp://192.168.1.2:6502", //source URL
"options": [ //source switching options
[
"priority",
"1"
],
[
"source_timeout",
"30"
]
]
}
],
"stats": {
"alive": true, //true if there are recent frames in the stream
"bitrate": 3690, //biteate
"bufferings": 0,
"client_count": 0, //number of clients (viewers) of this stream
"dash": true, //DASH enabled
"dvr_enabled": false, //archive recording disabled
"hds": true, //HDS enabled
"hls": true, //HLS enabled
"input_error_rate": 0, //number of errors registered per second
"last_access_at": 1493279230436,
"media_info": { //stream content info
"height": 576, //image height
"streams": [
{
"bitrate": 191, //biteate
"codec": "mp2a", //codec
"content": "audio", //content type:audio
"lang": "eng", //language
"track_id": "a1" //track number
},
{
"bitrate": 3256, //bitrate
"codec": "mp2v", //codec
"content": "video", //content type: video
"size": "1024x576", //image size
"track_id": "v1" //track number
}
],
"width": 1024 //image width
},
"out_bandwidth": 4002, //out bandwidth
"push_stats": { //stream copy statistisc, bytes
"tshttp://container4:8080/static1/mpegts": 2000918592
},
"remote": false, //the stream is not repeated from another Flussonic
"retry_count": 0, //number of automatic retries
"running": true, //stream is being broadcased, does not necessarily mean there are frames in the stream
"start_running_at": 1493279194382,
"ts_delay": 113, //milliseconds since the most recent frame in the stream
"url": "tshttp://192.168.1.2:6502" //URL of current source
},
"options": { //stream configuration
"static": false,
"retry_limit": 10,
"clients_timeout": 60,
"source_timeout": 60,
"pushes": [
[
"tshttp://container4:8080/static1/mpegts"
]
],
"publish_enabled": false,
"add_audio_only": false,
"dash_off": false,
"dvr_protected": false,
"hds_off": false,
"hls_off": false,
"m4s_off": false,
"mpegts_off": false,
"pulse_off": false,
"rtmp_off": false,
"rtsp_off": false,
"webrtc_off": false
}
}
},
...
]
因此獲得的數據,如果我想要得到的視頻比特率,我必須這樣寫:
video_bitrate: data.value.stats.media_info.streams[1].bitrate
但有時速率值不存在,拋出異常。我不想要那個,我該如何檢查?
一個辦法是,我發現我必須寫:
if(data.hasOwnProperty('value')) {
if (data.value.hasOwnProperty('value')) {
...
if(data.value.stats.media_info.streams[1].hasOwnerProperty('bitrate') {...}
}
}
但它太長而醜陋的方式。我還可以做些什麼?