【问题标题】:Python 27 CSV to JSON POSTPython 27 CSV 到 JSON POST
【发布时间】:2014-02-05 15:11:15
【问题描述】:

我正在将我的电影评分从 IMDB 转移到 Trakt。我使用 Python 脚本来执行此操作,但无法将我的列表转换为可序列化的 JSON。 我的脚本由一个 JSON 上传器和一个 CSV 阅读器组成,两者都可以单独工作。

我研究了列表与元组、json.dumps 选项和语法以及 json.encoder。网上有很多关于该主题的内容,但没有完整的 CSV 到 JSON 示例。

以下脚本包含所有步骤和几行示例数据。如果你想测试这个脚本,你需要 Trakt 账户的用户名、pass-SHA1 和 API 密钥。


当前错误:

raise TypeError(repr(o) + " is not JSON serializable") 
TypeError: `enter code here`set(['["tt1535108", "Elysium", "8", "2013"]']) is not JSON
serializable

#===============================================================================
# Used CSV file (imdb_ratings.csv)
#===============================================================================
# position,const,created,modified,description,Title,Title type,Directors,You rated,IMDb Rating,Runtime (mins),Year,Genres,Num. Votes,Release Date (month/day/year),URL
# 1,tt1683526,Sat Feb  1 00:00:00 2014,,,Detachment,Feature Film,Tony Kaye,8,7.7,97,2011,drama,36556,2011-04-25,http://www.imdb.com/title/tt1683526/
# 2,tt1205537,Wed Jan 29 00:00:00 2014,,,Jack Ryan: Shadow Recruit,Feature Film,Kenneth Branagh,6,6.6,105,2014,"action, mystery, thriller",11500,2014-01-15,http://www.imdb.com/title/tt1205537/
# 3,tt1535108,Tue Jan 28 00:00:00 2014,,,Elysium,Feature Film,Neill Blomkamp,8,6.7,109,2013,"action, drama, sci_fi, thriller",176354,2013-08-07,http://www.imdb.com/title/tt1535108/

#===============================================================================
# Imports etc.
#===============================================================================
import csv
import json
import urllib2

ifile  = open('imdb_ratings.csv', "rb")
reader = csv.reader(ifile)
included_cols = [1, 5, 8, 11]

#===============================================================================
# CSV to JSON
#===============================================================================
rownum = 0
for row in reader:
    # Save header row.
    if rownum == 0:
        header = row
    else:
        content = list(row[i] for i in included_cols)
        print(content)

    rownum += 1

ifile.close()

#===============================================================================
# POST of JSON
#===============================================================================
data = {
    "username": "<username>",
    "password": "<SHA1>",
    "movies": [
                 {
                 # Expected format: 
                 # "imdb_id": "tt0114746",
                 # "title": "Twelve Monkeys",
                 # "year": 1995,
                 # "rating": 9
                 json.dumps(content)
                 }

              ]
        }

req = urllib2.Request('http://api.trakt.tv/rate/movies/<api>')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))

【问题讨论】:

    标签: python json python-2.7 csv


    【解决方案1】:

    构造字典:

    {
    "imdb_id": "tt0114746",
    "title": "Twelve Monkeys",
    "year": 1995,
    "rating": 9
    }
    

    而不是调用json.dumps(content),它会创建一个字符串。

    您可以使用list comprehensiondict comprehension 创建字典列表:

    movies = [{field:row[i] for field, i in zip(fields, included_cols)} for row in reader]
    

    import csv
    import json
    import urllib2
    
    with open('imdb_ratings.csv', "rb") as ifile:
        reader = csv.reader(ifile)
        next(reader)  # skip header row
        included_cols = [1, 5, 8, 11]
        fields = ['imdb_id', 'title', 'rating', 'year']
        movies = [{field: row[i] for field, i in zip(fields, included_cols)}
                  for row in reader]
    
    data = {"username": "<username>",
            "password": "<SHA1>",
            "movies": movies}
    
    req = urllib2.Request('http://api.trakt.tv/rate/movies/<api>')
    req.add_header('Content-Type', 'application/json')
    
    response = urllib2.urlopen(req, json.dumps(data))
    

    【讨论】:

    • 谢谢!美丽的。对于使用此功能的鲁莽复制/粘贴者(如我):“年份”和“评级”列已切换:) 翻转第 8 列和第 11 列进行修复。
    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 2017-07-29
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多