Unable to serialize json array object returned from rest api in python

Question:

I am getting a rest api response from google cloud in json format

I assign this response in a python script(3.7) to a dictionary object row={} for inserting to bigquery

"upgrade": {
            "distribution": {
                "cpeUri": "cpe:/o:centos:centos:7",
                "classification": "Unknown",
                "severity": "Unknown"
                "cve": [
                    "CVE-2020-3288"
                ]
            }
        }

i assign these to the dictionary objects like this:

row["cpeUri"]=upgrade.distribution.cpeUri
row["cve"]=upgrade.distribution.cve //**This line gives me the following error:**

root        : INFO     CVE List ['CVE-2020-3288']
root        : ERROR    **Object of type Repeated is not JSON serializable**
Traceback (most recent call last):
  File "compliance_report.py", line 409, in main
    publish_bigquery(occurrenceslist,projectid,batch_id,batch_start_time)
  File "compliance_report _latest.py", line 165, in publish_bigquery
    row["cve"]=json.dumps(occurrenceresponse.upgrade.distribution.cve)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Repeated is not JSON serializable
root        : ERROR
------------------------------Exception
  1. if the change the code to

    row["cve"]=json.dumps(upgrade.distribution.cve)

I am still getting the same error.

All the other fields are working. Can anyone please suggest a solution?

Asked By: user1403505

||

Answers:

The following changes have worked for me:

cve_list = []

 for obj in occurrenceresponse.upgrade.distribution.cve:
   cve_list.append(obj)
 row["cve"]=cve_list

Now I don’t get a serialization error.

Answered By: user1403505
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.