JSON到python字典:打印值

2024-05-23 17:08:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这里没有。我有大量的json文件,每一个都是一系列不同语言的博客文章。键值对是关于帖子的元数据,例如“{author':'John Smith',”translator':'Jane Doe'}。我想做的是把它转换成一个python字典,然后提取值,这样我就有了所有文章中所有作者和翻译人员的列表。

for lang in languages:
   f = 'posts-' + lang + '.json'
   file = codecs.open(f, 'rt', 'utf-8')
   line = string.strip(file.next())
   postAuthor[lang] = []
   postTranslator[lang]=[]

   while (line):
      data = json.loads(line)
      print data['author']
      print data['translator']

当我尝试这种方法时,我一直得到一个翻译的关键错误,我不知道为什么。我以前从未使用过json模块,所以我尝试了一种更复杂的方法来查看发生了什么:

  postAuthor[lang].append(data['author'])
  for translator in data.keys():
      if not data.has_key('translator'):
           postTranslator[lang] = ""
      postTranslator[lang] = data['translator']

它一直返回一个错误,即字符串没有append函数。这似乎是一个简单的任务,我不知道我做错了什么。


Tags: 方法injsonlangfordata错误line
1条回答
网友
1楼 · 发布于 2024-05-23 17:08:27

看看这是否适合你:

import json

# you have lots of "posts", so let's assume
# you've stored them in some list. We'll use
# the example text you gave as one of the entries
# in said list

posts = ["{'author':'John Smith', 'translator':'Jane Doe'}"]

# strictly speaking, the single-quotes in your example isn't
# valid json, so you'll want to switch the single-quotes
# out to double-quotes, you can verify this with something
# like http://jsonlint.com/
# luckily, you can easily swap out all the quotes programmatically

# so let's loop through the posts, and store the authors and translators
# in two lists
authors = []
translators = []

for post in posts:
    double_quotes_post = post.replace("'", '"')
    json_data = json.loads(double_quotes_post)

    author = json_data.get('author', None)
    translator = json_data.get('translator', None)

    if author: authors.append(author)
    if translator: translators.append(translator)

# and there you have it, a list of authors and translators

相关问题 更多 >