title: How to write elements in nested children of a JSON file using Python
body: <p>I have a JSON file like this.</p>
  <pre><code>{
  
      &quot;posts&quot;: [{
          &quot;id&quot;: 0,
          &quot;title&quot;: &quot;title1&quot;,
          &quot;author&quot;: &quot;CIQ&quot;,
          &quot;views&quot;: 100,
          &quot;reviews&quot;: 31
      }],
      &quot;authors&quot;: [{
          &quot;id&quot;: 0,
          &quot;first_name&quot;: &quot;Commerce&quot;,
          &quot;last_name&quot;: &quot;IQ&quot;,
          &quot;posts&quot;: 45
      }]
  }
  </code></pre>
  <p>I want to write the values in nested children of JSON eg. Add the following Post and save the same JSON file.</p>
  <pre><code>   {
          &quot;id&quot;: 1,
          &quot;title&quot;: &quot;title2&quot;,
          &quot;author&quot;: &quot;CIQ2&quot;,
          &quot;views&quot;: 100,
          &quot;reviews&quot;: 31
      }
  </code></pre>
  <p>The final file will look like.</p>
  <pre><code>{
  &quot;posts&quot;: [{
      &quot;id&quot;: 0,
      &quot;title&quot;: &quot;title1&quot;,
      &quot;author&quot;: &quot;CIQ&quot;,
      &quot;views&quot;: 100,
      &quot;reviews&quot;: 31
  }, {
      &quot;id&quot;: 1,
      &quot;title&quot;: &quot;title2&quot;,
      &quot;author&quot;: &quot;CIQ2&quot;,
      &quot;views&quot;: 100,
      &quot;reviews&quot;: 3
  }],
  &quot;authors&quot;: [{
      &quot;id&quot;: 0,
      &quot;first_name&quot;: &quot;Commerce&quot;,
      &quot;last_name&quot;: &quot;IQ&quot;,
      &quot;posts&quot;: 45
  }]
  </code></pre>
  <p>}</p>
  <p>I am using the below script for writing the file.</p>
  <pre><code>with open(file_path, 'r+') as json_file:
              data = json.load(json_file)
              data['posts'].append(new_post)
              json_file.write(json.dumps(data, ensure_ascii=True))
  </code></pre>
  <p>problem with this script is it appends the data after the end of the file. as shown in the image.
  <a href="https://i.stack.imgur.com/1cN5b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1cN5b.png" alt="enter image description here" /></a></p>
  <p>Please suggest some apporach.</p>