我正在尝试从http调用解析json。为此,我写了http调用,我得到了像this
这样的数据[ //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') {...}
}
}
但它太长而且丑陋。我还能做什么?
答案 0 :(得分:1)
您可以使用jsonpath:
var jp = require('jsonpath');
var bitrates = jp.query(data, '$..streams[1].bitrate');
答案 1 :(得分:0)
尝试javascript的三元运算符:D https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
const has_it = data.hasOwnProperty('value') ? true : false;