JSON to python dictionary:打印值

时间:2011-07-18 19:32:48

标签: python json dictionary

Noob在这里。我有大量的json文件,每个文件都是一系列不同语言的博客文章。键值对是关于帖子的元数据,例如“{'作者':'John Smith','翻译':'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']

它不断返回字符串没有追加功能的错误。这似乎是一项简单的任务,我不确定我做错了什么。

1 个答案:

答案 0 :(得分:2)

看看这是否适合你:

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