title: How to replace a value in json file using python
body: <p>My task is to replace a value in the json file.</p>
  <p>my json file is below. Here I need to replace below values.</p>
  <ol>
  <li>replace  &quot;ServicePort&quot;: &quot;0008&quot;, to value 0012</li>
  <li>replace  &quot;PService&quot;: &quot;13.3.13.3&quot;,  to value  13.12.12.12</li>
  <li>replace  &quot;username&quot;: &quot;root&quot;,  to &quot;xyz&quot;</li>
  </ol>
  <p>My json file</p>
  <pre><code>{
    &quot;version&quot;: &quot;35.1&quot;,
    &quot;ServicePort&quot;: &quot;0008&quot;,
    &quot;APIService&quot;: &quot;14.414.4&quot;,
    &quot;Storage&quot;: [
      {
        &quot;PService&quot;: &quot;13.3.13.3&quot;,
        &quot;username&quot;: &quot;root&quot;,
        &quot;Number&quot;: 121,
        &quot;IP&quot;: &quot;10.2.10.2&quot;
      }
    ]
  }
  </code></pre>
  <p>My Python code to perform the above tasks is</p>
  <pre><code>import os
  import sys
  import json
  
  with open('/xyz/Test/Conf.json', 'r') as fh:
      json_data = json.load(fh)
  
      for item in json_data:
          if item['Number'] in [&quot;121&quot;]:
              item['Number'] = &quot;132&quot;
  
  with open('/xyz/Test/Conf.json', 'w') as fh:
      json.dump(json_data, fh, indent=2)
  
  
  
  </code></pre>
  <p>here I am unable to do the same and hitting with the below error, may some please help me whats going wrong with my code.</p>
  <p>Error:</p>
  <pre><code>    if item['Number'] in [&quot;121&quot;]:
  TypeError: string indices must be integers
  </code></pre>
  <p>Requirement 2:</p>
  <p>I have to slightly modify the code.  the requirement is to create dictionary from the file which contains the json parameters and their values.</p>
  <ol>
  <li>I have created a dictionary from the file called data</li>
  <li>I need to change the value of json file by assigning the dictionary value as mentioned in the code below</li>
  </ol>
  <p>change in the code - Assignment is from dictionary - which is not happening</p>
  <pre><code>D = {}
  with open(&quot;data&quot;) as f:
      for line in f:
          (key, val) = line.split()
          D[key] = val
  print(D)
  
  for item in json_data:
      print(item, &quot;: &quot;, type(item))
  
  print(&quot;-----------get keys and values from dict----------------&quot;)
  for key, value in json_data.items():
      print(key, &quot;: &quot;, type(key), value, &quot;: &quot;, type(value))
  
  print(&quot;----------try to change-----------------&quot;)
  for key, value in json_data.items():
      if key == &quot;Storage&quot;:
          for i in range(len(value)):
              if json_data[&quot;Storage&quot;][i][&quot;Number&quot;] == 121:
                  json_data[&quot;Storage&quot;][i][&quot;Number&quot;] = D['Number']  #  &lt;--- this is the change i need, may you please suggest any solution here, this assignment is not working
  
  print(json_data)
  </code></pre>