-3

I want to get the value of caller_id from the following string with JavaScript

{"dispnumber": "+XXXXXXXXXX", "extension": "1", "callid": "b7d14b81-68cf-4250-b5f2-fe486ef7b0b6", "destination": "+911762503777", "caller_id": "+91XXXSSSSSS", "action": "phone", "event": "connected"}

How do I do that?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
user3286692
  • 383
  • 1
  • 5
  • 23

3 Answers3

2

The data what you have shown looks like a valid JSON data. Just parse it like this

var obj = JSON.parse(string_data);

which will give you a valid JavaScript object and then you can get the caller_id property like this

console.log(obj.caller_id);
# +91XXXSSSSSS
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

try something like this

    // 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
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
0

We can assign the string to the variable and it treats as objects. Using objectname.keyname i.e (json.caller_id), we can get the value.

    <!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>

We can also get the value by making it string and using JSON.parse converts into object

    <!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>