简体   繁体   中英

How save a json file in python from api response when the class is a list and object is not serializable

I have tried to find the answer but I could not find it

I am looking for the way to save in my computer a json file from python.

I call the API

configuration = api.Configuration()
configuration.api_key['X-XXXX-Application-ID'] = 'xxxxxxx'
configuration.api_key['X-XXX-Application-Key'] = 'xxxxxxxx1'

## List our parameters as search operators
opts= {
    'title': 'Deutsche Bank',
    'body': 'fraud',
    'language': ['en'],
    'published_at_start': 'NOW-7DAYS',
    'published_at_end': 'NOW',
    'per_page': 1,
    'sort_by': 'relevance'
}

try:
    ## Make a call to the Stories endpoint for stories that meet the criteria of the search operators
    api_response = api_instance.list_stories(**opts)
    ## Print the returned story
    pp(api_response.stories)
except ApiException as e:
    print('Exception when calling DefaultApi->list_stories: %s\n' % e)

I got the response like this

[{'author': {'avatar_url': None, 'id': 1688440, 'name': 'Pranav Nair'},
 'body': 'The law firm will investigate whether the bank or its officials have '
         'engaged in securities fraud or unlawful business practices. '
         'Industries: Bank Referenced Companies: Deutsche Bank',
 'categories': [{'confident': False,
                 'id': 'IAB11-5',
                 'level': 2,
                 'links': {'_self': 'https://,
                           'parent': 'https://'},
                 'score': 0.39,
                 'taxonomy': 'iab-qag'},
                {'confident': False,
                 'id': 'IAB3-12',
                 'level': 2,
                 'links': {'_self': 'https://api/v1/classify/taxonomy/iab-qag/IAB3-12',
                 'score': 0.16,
                 'taxonomy': 'iab-qag'},
 'clusters': [],
 'entities': {'body': [{'indices': [[168, 180]],
                        'links': {'dbpedia': 'http://dbpedia.org/resource/Deutsche_Bank'},
                        'score': 1.0,
                        'text': 'Deutsche Bank',
                        'types': ['Bank',
                                  'Organisation',
                                  'Company',
                                  'Banking',
                                  'Agent']},
                       {'indices': [[80, 95]],
                        'links': {'dbpedia': 'http://dbpedia.org/resource/Securities_fraud'},
                        'score': 1.0,
                        'text': 'securities fraud',
                        'types': ['Practice', 'Company']},
 'hashtags': ['#DeutscheBank', '#Bank', '#SecuritiesFraud'],
 'id': 3004661328,
 'keywords': ['Deutsche',
              'behalf',
              'Bank',
              'firm',
              'investors',
              'Deutsche Bank',
              'bank',
              'fraud',
              'unlawful'],
 'language': 'en',
 'links': {'canonical': None,
           'coverages': '/coverages?story_id=3004661328',
           'permalink': 'https://www.snl.com/interactivex/article.aspx?KPLT=7&id=58657069',
           'related_stories': '/related_stories?story_id=3004661328'},
 'media': [],
 'paragraphs_count': 1,
 'published_at': datetime.datetime(2020, 5, 19, 16, 8, 5, tzinfo=tzutc()),
 'sentences_count': 2,
 'sentiment': {'body': {'polarity': 'positive', 'score': 0.599704},
               'title': {'polarity': 'neutral', 'score': 0.841333}},
 'social_shares_count': {'facebook': [],
                         'google_plus': [],

 'source': {'description': None,
            'domain': 'snl.com',
            'home_page_url': 'http://www.snl.com/',
            'id': 8256,
            'links_in_count': None,
            'locations': [{'city': 'Charlottesville',
                           'country': 'US',
                           'state': 'Virginia'}],
            'logo_url': None,
            'name': 'SNL Financial',
            'scopes': [{'city': None,
                        'country': 'US',
                        'level': 'national',
                        'state': None},
                       {'city': None,
                        'country': None,
                        'level': 'international',
                        'state': None}],
            'title': None},
 'summary': {'sentences': ['The law firm will investigate whether the bank or '
                           'its officials have engaged in securities fraud or '
                           'unlawful business practices.',
                           'Industries: Bank Referenced Companies: Deutsche '
                           'Bank']},
 'title': "Law firm to investigate Deutsche Bank's US ops on behalf of "
          'investors',
 'translations': {'en': None},
 'words_count': 26}]

In the documentation says "Stories you retrieve from the API are returned as JSON objects by default. These JSON story objects contain 22 top-level fields, whereas a full story object will contain 95 unique data points"

The class is a list. When I have tried to save json file I have the error "TypeError: Object of type Story is not JSON serializable".

How I can save a json file in my computer?

The response you got is not json, json uses double quotes, but here its single quotes. Copy paste your response in the following link to see the issues http://json.parser.online.fr/ .

If you change it like [{"author": {"avatar_url": None, "id": 1688440, "name": "Pranav Nair"}, "body": "......

It will work, You can use python json module to do it

import json
json.loads(the_dict_got_from_response).

But it should be the duty of the API provider to, To make it working you can json load the result you got.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM