Python:如何进行更改并添加到json中

时间:2015-12-13 01:20:29

标签: python json parsing

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

基本上我想添加另一个博客条目并插入我自己的变量并添加到我已有的。

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

在那里使用该模板如何插入变量并添加到我的json文件中。

我试图让最终结果看起来像这样

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


],

我尝试使用link,我一直在网上搜索如何做这样的事情。

2 个答案:

答案 0 :(得分:2)

由于您可能感兴趣的内容很多,我写了一个小代码来演示您在开始时应该注意的基础知识:

  • 阅读文件
  • Python词典(它们如何工作,如何访问键和值,如何更新它们......)
  • Python列表(它们如何工作,如何访问元素,......)
  • Python的json模块(加载和转储数据,从JSON转换为Python的数据类型,......)

假设您有一个名为blog_entries.json的JSON文件,其中包含以下内容:

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

我们可以加载这个文件并进行一些数据操作。请参阅代码中的注释以获取更多详细信息:

#!/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)

答案 1 :(得分:1)

使用追加:

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/js/bootstrap.min.js"></script>
<div class="row">
  <form action="#">
    <table>
      <tr>
        <td>First Name </td>
        <td>:</td>
        <td>
          <input type="text" id="first_name" required>
        </td>
      </tr>
      <tr>
        <td>Last Name</td>
        <td>:</td>
        <td>
          <input type="text" id="last_name" required>
        </td>
      </tr>
      <tr>
        <td>Age</td>
        <td>:</td>
        <td>
          <input type="text" id="age" required>
        </td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <!-- <td><input type="submit" value="Submit" id="submit"></td> -->
        <td>
          <input type="submit" value="Submit" id="submit" class="btn">
        </td>
      </tr>
    </table>
  </form>
</div>
<div class="modal fade hide" id="confirm-save" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel"><b>Are you sure to book this tour?</b></h4>
      </div>

      <div class="modal-body">
        <table style="width:100%">
          <tr>
            <td style="width:30%">First Name</td>
            <td height top="40" style="width:70%" id="first_name_modal"></td>
          </tr>
          <tr>
            <td>Last Name</td>
            <td height="40" id="last_name_modal"></td>
          </tr>
          <tr>
            <td>Age</td>
            <td height="40" id="age_modal"></td>
          </tr>
        </table>
        <p class="debug-url"></p>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Save changes</button>&nbsp;
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>