-1
{
    "blogs": [
         {
          "header": "Welcome",
         "author": "Auriga",
         "team"  : "Webmaster",
         "date"  : ["2015", "12", "12"],
         "paragraphs" : [
          "Blah blah blah"
       ],
        "images": []
    }
],

Basically I want to add this another blog entry and insert my own variables and add onto what I already have.

       {
         "header": "",
         "author": "",
         "team"  : "",
         "date"  : ["", "", ""],
         "paragraphs" : [
          ""
       ],
        "images": []
    },

Using that template up there how do I insert variables and add into my json file.

I'm trying to make the end result look like this

{
  "blogs": [
     {
      "header": "Welcome",
      "author": "Auriga",
      "team"  : "Webmaster",
      "date"  : ["2015", "12", "12"],
      "paragraphs" : [
      "Blah blah blah"
    ],
     "images": []
  },
  {
      "header": "BLah blah",
      "author": "Blah blah",
      "team"  : "Blah Blah Blah",
      "date"  : ["2015", "12", "12"],
      "paragraphs" : [
      "Blah blah blah"
    ],
     "images": []
  },      


],

I tried using link and I have been just stuck searching online how to do something like this.

Community
  • 1
  • 1
maxadorable
  • 1,290
  • 1
  • 10
  • 24

2 Answers2

2

Since there are a lot of things you might be interested I wrote a small code to demonstrate the basics you should take care about at the beginning:

  • Reading files
  • Python dictionaries (how they work, how to access keys and values, how to update them, ...)
  • Python lists (how they work, how to access elements, ...)
  • Python's json module (loading and dumping data, conversion from JSON to Python's datatypes, ...)

Assuming you have a JSON-file called blog_entries.json with the following contents:

[{
    "header": "First Story",
    "author": "Tim",
    "team": "department one",
    "date": ["2015", "12", "12"],
    "paragraphs": ["First para", "Second para"],
    "images": []
}, {
    "header": "Second Story",
    "author": "Steven",
    "team": "department two",
    "date": ["2015", "12", "12"],
    "paragraphs": ["First para", "Second para"],
    "images": []
}, {
    "header": "Third Story",
    "author": "Bob",
    "team": "department three",
    "date": ["2015", "12", "12"],
    "paragraphs": ["First para", "Second para"],
    "images": []
}, {
    "header": "Fourth Story",
    "author": "John",
    "team": "department four",
    "date": ["2015", "12", "12"],
    "paragraphs": ["First para", "Second para"],
    "images": []
}]

We can load this file and do some data manipulation. Please see comments in code for further details:

#!/usr/bin/env python3
# coding: utf-8


# use json module to handle json-formatted data in python
import json


new_entry = {"header": "The story to be added",
    "author": "me",
    "team": "editor",
    "date": ["2015", "12", "13"],
    "paragraphs": ["First para", "Second para"],
    "images": []
    }


update_entry = {"header": "Formerly written by John",
    "author": "me"
    }


# Use `with open()` in order to open a file and close it automatically after all operations are done.
with open('blog_entries.json') as f:
    existing_entries = json.load(f)

# Before starting any manipulation print the existing blog entries in order to double-check.
# Use `json.dumps()` in order to get a nicely formatted output
print(json.dumps(existing_entries, sort_keys=True, indent=4))


# Since `json.load()` converts the json data to the appropiate Python datatype (list or dict) we can use Python's
# standard operations for those datatypes.
# `exiting_blogs` will be a list since it's an array in the json-formatted file (an object would become a dict),
# so we append the new blog entry and print it again in order to double-check
existing_entries.append(new_entry)
print(json.dumps(existing_entries, sort_keys=True, indent=4))


# OK, let's say we want to manipulate the blog entry which was written by John.
# First, we have to find the desired data in the list.
for entry in existing_entries:
    if entry['author'] == 'John':
        # Update the existing entry (of datatype dict) with the new elements which will overwrite the old ones.
        entry.update(update_entry)
    else:
        # We did not find any entry written by John. Think about this error case later...
        pass


# This output will show that the entry written by John was updated with the data given in `update_enry`.
print(json.dumps(existing_entries, sort_keys=True, indent=4))


# Write the manipulated data to a new file.
# For sure, we could use the same file as we read from, but this would make comparing the file contents somehow
# difficult
with open('new_blog_entries.json', 'w') as f:
    json.dump(existing_entries, f)
albert
  • 8,027
  • 10
  • 48
  • 84
1

Use append:

import json
data = {
    "blogs": [
         {
          "header": "Welcome",
         "author": "Auriga",
         "team"  : "Webmaster",
         "date"  : ["2015", "12", "12"],
         "paragraphs" : [
            "Blah blah blah"
        ],
        "images": []
        }
    ],
}

print(json.dumps(data.get('blogs'), indent=2))

more_data = {
         "header": "",
         "author": "",
         "team"  : "",
         "date"  : ["", "", ""],
         "paragraphs" : [
          ""
       ],
        "images": []
    }

data['blogs'].append(more_data)

print(json.dumps(data, indent=2))
fiacre
  • 1,150
  • 2
  • 9
  • 26