0

I am using RingCentral API to get call log information.

I am interested in an attribute called from which tells us who was the caller who made the call. To access the caller name, I need to access a call record -> then go to the last leg (root of the call) and then get the from attribute, and then get the name of the caller.

E.g:

"from": { "name": "andy murray", "phoneNumber": "+44712345656" }

resp = platform.get('/restapi/v1.0/account/~/call-log', params)       
for record in resp.json().records:
    print(record.legs[-1].from.name)

After running this command, I am getting error:

      File "demo.py", line 43
        print(record.legs[-1].from.name )
SyntaxError: invalid syntax

It looks like Python is not able to comprehend that this "from" is not part of Python itself. How can I define Python to consider this as an attribute of a JSON object?

Any help will be appreciated!

Grokify
  • 15,092
  • 6
  • 60
  • 81
  • 1
    A JSON object loads as a Python dict. You need to use slicing - `record.legs[-1]['from']['name']` for example - rather than attribute access. Since the keys are now just strings, it's no longer a problem that `from` is a Python keyword. – jasonharper Nov 23 '20 at 13:22
  • @jasonharper I am not converting it into python dict. It is working for all other attributes like : record.legs[-1].recording.uri. It just fails when I try to access "from" attribute – Hassaan Anwar Nov 23 '20 at 13:31
  • Then it would appear that you aren't using Python's standard `json` module. I'd still suggest trying slicing, at least for this one attribute name. The alternative would be to use `getattr(x, 'from')`. – jasonharper Nov 23 '20 at 13:35
  • Thanks mate. I found a workaround, I tried getattr, but still got the same error. Then, I called record.legs[-1].__dict__ and found out all attributes of json object. I found that, there was no attribute named "from", it was "from_". However, with postman I was getting "from" attribute, I guess its the way python handles json objects (by renaming "from" to "from_" to avoid conflicts?) – Hassaan Anwar Nov 23 '20 at 14:18
  • What library are you using? This isn't Python's standard JSON parser. – Charles Duffy Dec 01 '20 at 01:02
  • I am using sdk of RingCentral, making API calls to fetch data. Data is returned in an "ApiResponse" format. I convert that into .json. Using object.json() method. – Hassaan Anwar Dec 01 '20 at 12:40

1 Answers1

0

Use __dict__ to get all attributes of object. https://stackoverflow.com/a/39392891/9024042

As mentioned in the answer of the attached post. I called record.legs[-1].__dict__ and found out all attributes of json object.

I found that, there was no attribute named "from", It was "from_".

I hope it helps someone with the same issue