久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

無法使用python讀取json文件。獲取類型錯誤:json對象為“ TextIOWrapper”

瀏覽:60日期:2022-08-07 09:32:06
如何解決無法使用python讀取json文件。獲取類型錯誤:json對象為“ TextIOWrapper”?

json.load()用于加載文件。json.loads()與字符串一起使用。

解決方法

我正在嘗試從json文件讀取。

這是我創(chuàng)建文件的方式:

import requestsimport jsonimport timefrom pprint import pprintBASE_URL = 'https://www.wikiart.org/en/api/2/UpdatedArtists'artist_json_data = requests.get(BASE_URL).json()with open(’artistdata.json’,’w’) as outfile: while artist_json_data[’hasMore’]:print(artist_json_data[’paginationToken’])url = BASE_URL + '?paginationToken=' +artist_json_data[’paginationToken’]artist_json_data = requests.get(url).json()json.dump(artist_json_data,outfile,indent=4)time.sleep(1)

這是我輸出的開始:

{ 'data': [{ 'id': '57726da5edc2cb3880b4ca54','artistName': 'Paul Feeley','url': 'paul-feeley','lastNameFirst': 'Feeley Paul','birthDay': '/Date(-1893456000000)/','deathDay': '/Date(-126230400000)/',

當我嘗試使用以下代碼讀取同一文件時:

from pprint import pprintwith open(’artistdata.json’,’r’,encoding=’utf-8’) as data_file:data = json.loads(data_file) pprint(data)

我得到錯誤

TypeError: the JSON object must be str,bytes or bytearray,not ’TextIOWrapper’

我不明白,因為我可以像往常一樣崇高地打開文件。我該如何處理?

使用以下代碼解決了該問題:

問題是我混合了轉(zhuǎn)儲和負載。現(xiàn)在我正在使用轉(zhuǎn)儲和加載

class Wikiart: ’’’Class to access wikiart.org Data’’’ def __init__(self):self.BASE_URL = 'https://www.wikiart.org/en/'self.BASE_URL_API = self.BASE_URL + 'api/2/'self.BASE_URL_MOVEMENT = self.BASE_URL + ’artists-by-art-movement/’self.ARTIST_DATA_URL = self.BASE_URL_API + 'UpdatedArtists' def write_artist_data_into_json_file(self): artists = requests.get(ARTIST_DATA_URL).json() all_artists = artists[’data’] with open(’artistdata.json’,’w’) as outfile:while artists[’hasMore’]: print(’fetching next: pagination token’,artists[’paginationToken’]) url = BASE_URL + '?paginationToken=' + artists[’paginationToken’] artists_next_page = requests.get(url).json() next_artists = artists_next_page[’data’] time.sleep(0.25) all_artists = all_artists + next_artists artists = artists_next_pagejson.dump(all_artists,indent=4)from pprint import pprintwith open(’artistdata.json’,encoding=’utf-8’) as data_file:data = json.load(data_file) pprint(data)

標簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 个旧市| 龙泉市| 淄博市| 泾源县| 塔城市| 石屏县| 正安县| 大名县| 灵璧县| 神木县| 宽城| 海盐县| 涟水县| 黄平县| 海口市| 孝感市| 平顶山市| 社旗县| 贵南县| 恩平市| 乌拉特中旗| 哈巴河县| 永兴县| 尚义县| 安乡县| 临潭县| 湖北省| 沅陵县| 车险| 晋江市| 菏泽市| 黄梅县| 宣威市| 罗城| 义乌市| 苗栗县| 青河县| 天门市| 抚州市| 辽阳县| 阿荣旗|