我希望使用JavaScript
从以下字符串中获取caller_id
的值
{"dispnumber": "+XXXXXXXXXX", "extension": "1", "callid": "b7d14b81-68cf-4250-b5f2-fe486ef7b0b6", "destination": "+911762503777", "caller_id": "+91XXXSSSSSS", "action": "phone", "event": "connected"}
我该怎么做?
答案 0 :(得分:2)
您显示的数据看起来像是有效的JSON数据。只需像这样解析它
var obj = JSON.parse(string_data);
将为您提供有效的JavaScript对象,然后您可以获得caller_id
这样的属性
console.log(obj.caller_id);
# +91XXXSSSSSS
答案 1 :(得分:0)
尝试这样的事情
// if it is javscript object
var obj = {"dispnumber": "+XXXXXXXXXX", "extension": "1", "callid": "b7d14b81-68cf-4250-b5f2-fe486ef7b0b6", "destination": "+911762503777", "caller_id": "+91XXXSSSSSS", "action": "phone", "event": "connected"};
obj.caller_id;//+91XXXSSSSSS
// if it is string
var str = '{"dispnumber": "+XXXXXXXXXX", "extension": "1", "callid": "b7d14b81-68cf-4250-b5f2-fe486ef7b0b6", "destination": "+911762503777", "caller_id": "+91XXXSSSSSS", "action": "phone", "event": "connected"}';
var obj = JSON.parse(str);
obj.caller_id;//+91XXXSSSSSS
答案 2 :(得分:0)
我们可以将字符串分配给变量,并将其视为对象。使用objectname.keyname,即(json.caller_id),我们可以获得值。
<!DOCTYPE html>
<html>
<body>
<script>
var json = {"dispnumber": "+XXXXXXXXXX", "extension": "1", "callid": "b7d14b81-68cf-4250- b5f2-fe486ef7b0b6","destination": "+911762503777", "caller_id": "+91XXXSSSSSS", "action": "phone", "event": "connected"};
alert(json.caller_id);
</script>
</body>
</html>
我们也可以通过使它成为字符串并使用JSON.parse转换为对象
来获取值 <!DOCTYPE html>
<html>
<body>
<script>
var obj = '{"dispnumber": "+XXXXXXXXXX", "extension": "1", "callid": "b7d14b81-68cf-4250- b5f2-fe486ef7b0b6","destination": "+911762503777", "caller_id": "+91XXXSSSSSS", "action": "phone", "event": "connected"}';
var json = JSON.parse(obj);
alert(json.caller_id);
</script>
</body>
</html>