Словарь JSON в python: печать значений - PullRequest
2 голосов
/ 18 июля 2011

Нуб здесь. У меня есть большое количество файлов JSON, каждый из которых представляет собой серию сообщений в блогах на разных языках. Пары ключ-значение являются метаданными о сообщениях, например "{'author': 'John Smith', 'translationator::' 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 Ответ

2 голосов
/ 19 июля 2011

Посмотрите, работает ли это для вас:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...