Home:ALL Converter>Python: Write JSON dictionary values to a JSON file

Python: Write JSON dictionary values to a JSON file

Ask Time:2018-04-26T03:02:48         Author:AWalton

Json Formatter

I am attempting to:

  1. Load data from a JSON list of dictionaries
  2. Write the values of a specific key from each dictionary to a file

Yet, when I attempt to dump the key pairs to the new .json file, it only prints the very last dictionary key pair. Anyone know how to loop through each dictionary and append the key pair? I have tried a few methods but I can't seem to figure out what i'm missing and where.

Here is my code:

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')

A sample of my JSON file:

{ 
    "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"
    }
    ]
}

My current output:

"text: grapes"

But, I want to loop through every dictionary and eventually print only the values from each "text" key.

Expected Output:

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

Any hints will help! Thanks!

Author:AWalton,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50029624/python-write-json-dictionary-values-to-a-json-file
Nishant Nawarkhede :

You have opened file in w mode, you need to open it into a (append mode)\n\nfrom docs:\n\n1. 'w' for only writing (an existing file with the same name will be erased)\n\n2. 'a' opens the file for appending; any data written to the file is automatically added to the end\n\nPython 3.6.5 (default, Mar 30 2018, 06:42:10)\n[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 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'}]\n>>> import json\n>>> 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'}]\n>>> for d in my_list:\n... for key, value in d.items():\n... if key == \"text\":\n... with open('comments.json', 'a') as f: # Append mode here\n... json.dump(\"{}: {}\".format(key,value), f)\n... f.write('\\n')\n...\n\n\nContents of comments.json,\n\n\"text: apple\"\n\"text: orange\"\n\"text: grapes\"\n\n\nFile modes in Python,\n\n'r' open for reading (default)\n'w' open for writing, truncating the file first\n'x' open for exclusive creation, failing if the file already exists\n'a' open for writing, appending to the end of the file if it exists\n'b' binary mode\n't' text mode (default)\n'+' open a disk file for updating (reading and writing)\n'U' universal newlines mode (deprecated)\n",
2018-04-25T19:14:11
yy