Python: запись значений словаря JSON в файл JSON - PullRequest
0 голосов
/ 25 апреля 2018

Я пытаюсь:

  1. Загрузить данные из списка словарей JSON
  2. Записать значения определенного ключа из каждого словаря в файл

Тем не менее, когда я пытаюсь записать пары ключей в новый файл .json, он печатает только самую последнюю пару словарных ключей.Кто-нибудь знает, как перебрать каждый словарь и добавить пару ключей?Я попробовал несколько методов, но я не могу понять, что мне не хватает и где.

Вот мой код:

with open(join(dirname(__file__),'text.json')) as tone_json:
    python_obj = json.load(tone_json)       #read file object into string
    my_list = python_obj["data"]            #assign list name to string

for dictionary in my_list:                  #loop through dictionaries in list
    for key,value in dictionary.items():    #loop through key pairs in dictionaries
        if key == "text":
            with open('comments.json', 'w') as f:
                json.dump("{}: {}".format(key,value), f)    #write key pair objects as json formatted stream to json file
                f.write('\n')

Пример моего файла JSON:

{ 
    "data": [
    {
        "text": "apple",
        "created_time": "2017-12-23",
        "comment_count": 154,
        "like_count": 856,
        "id": "1015595299xxxxx"
    },
    {
        "text": "orange",
        "created_time": "2017-12-04",
        "comment_count": 13,
        "like_count": 437,
        "id": "10155952xxxxx"
    },
    {
        "text": "grapes",
        "created_time": "2017-12-04",
        "comment_count": 12,
        "like_count": 163,
        "id": "1015595299xxxxx"
    }
    ]
}

Мой текущий вывод:

"text: grapes"

Но я хочу пройтись по каждому словарю и в конечном итоге вывести только значения из каждого «текстового» ключа.

Ожидаемый результат:

"text: apple"
"text: orange"
"text: grapes"

Любые подсказки помогут!Спасибо!

Ответы [ 2 ]

0 голосов
/ 25 апреля 2018

Если я правильно вас понял, это должно сделать то, что вы хотите:

with open('comments.json', 'a') as f:
    json.dump("{}: {}".format(key,value), f)    #write key pair objects as json formatted stream to json file
    f.write('\n')

Просто замените 'w' на 'a', чтобы вы не перебирали w обряд, но a ppend с файлом

0 голосов
/ 25 апреля 2018

Вы открыли файл в режиме w, вам нужно открыть его в a (режим добавления)

из документов :

1.'w' только для записи (существующий файл с тем же именем будет удален)

2.«а» открывает файл для добавления;любые данные, записанные в файл, автоматически добавляются в конец

Python 3.6.5 (default, Mar 30 2018, 06:42:10)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> my_list = [{u'created_time': u'2017-12-23', u'text': u'apple', u'comment_count': 154, u'like_count': 856, u'id': u'1015595299xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'orange', u'comment_count': 13, u'like_count': 437, u'id': u'10155952xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'grapes', u'comment_count': 12, u'like_count': 163, u'id': u'1015595299xxxxx'}]
>>> import json
>>> my_list = [{u'created_time': u'2017-12-23', u'text': u'apple', u'comment_count': 154, u'like_count': 856, u'id': u'1015595299xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'orange', u'comment_count': 13, u'like_count': 437, u'id': u'10155952xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'grapes', u'comment_count': 12, u'like_count': 163, u'id': u'1015595299xxxxx'}]
>>> for d in my_list:
...     for key, value in d.items():
...             if key == "text":
...                     with open('comments.json', 'a') as f:  # Append mode here
...                             json.dump("{}: {}".format(key,value), f)
...                             f.write('\n')
...

Содержимое comments.json,

"text: apple"
"text: orange"
"text: grapes"

Режимы файлов в Python,

'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
...