Rubin
Rubin

Reputation: 31

Replacing words in JSON file using Python

smpl.json file:

[ 
   { 
      "add":"dtlz",
      "emp_details":[ 
         [ 
            "Shubham",
            "[email protected]",
            "intern"
         ],
         [ 
            "Gaurav",
            "[email protected]",
            "developer"
         ],
         [ 
            "Nikhil",
            "[email protected]",
            "Full Time"
         ]
      ]
   }
]

Python file:

import json 
 with open('smpl.json', 'r') as file:
 json_data = json.load(file)
   for item in json_data["emp_details"]:
     if item[''] in ['Shubham']:
        item[''] = 'Indra'
 with open('zz_smpl.json', 'w') as file:
   json.dump(json_data, file, indent=4)

Since I'm having trouble with the code. Any help would be great.

Looking forward for your help.Thanks in advance!!!

Upvotes: 2

Views: 392

Answers (3)

Blessed Geek
Blessed Geek

Reputation: 21684

1st, you need to understand list/arrays and maps data structures, and how they are represented by JSON. Seriously, you must understand those data structures in order to use JSON.

An empty array a1

a1 = []

Array with 3 integers

a2 = [1, 2, 3]

To address the 2nd value

a2[0] is 1st value
a2[1] is 2nd value

In python, to subset a2 into 2nd and 3rd value

a3 = a2[1:]

Maps/dicts are containers of key:value pairs. And empty map (called a dict in python)

d1 = {}

Maps with 2 pairs

d2 = { 'name' : 'Chandra Gupta Maurya' , 'age' : 2360 }
d3 = { 'street' : 'ashoka' , 'location' : 'windsor place' , 'city' : 'delhi' }

such that value of

d2['name'] is 'Chandra Gupta Maurya'

An array of two maps. When you do this in python (and javaScript)

ad1 = [ d2, d3 ]

you are equivalently doing this:

ad1 = [ 
        { 'name' : 'Chandra Gupta Maurya' , 'age' : 2360 } ,
        { 'street' : 'ashoka' , 'location' : 'windsor place' , 'city' : 'delhi' }
      ]

so that ad1[0] is

{ 'name' : 'Chandra Gupta Maurya' , 'age' : 2360 } 

Obviously "emp_details" is in position 0 of an array

json_data[0]['emp_details']

json_data[0]['emp_details'] itself is the key to an array of maps.

>>> json.dumps (json_data[0]["emp_details"] , indent=2)

produces

'[\n  [\n    "Shubham",\n    "[email protected]",\n    "intern"\n  ],\n  [\n    "Gaurav",\n    "[email protected]",\n    "developer"\n  ],\n  [\n    "Nikhil",\n    "[email protected]",\n    "Full Time"\n  ]\n]'

and

>>> print ( json.dumps (json_data[0]["emp_details"], indent=2) )

produces

[
  [
    "Shubham",
    "[email protected]",
    "intern"
  ],
  [
    "Gaurav",
    "[email protected]",
    "developer"
  ],
  [
    "Nikhil",
    "[email protected]",
    "Full Time"
  ]
]

Therefore,

>>> json_data[0]["emp_details"][1]
['Gaurav', '[email protected]', 'developer']

Then you might wish to do the replacement

>>> json_data[0]["emp_details"][1][2] = 'the rain in maine falls plainly insane'
>>> json_data[0]["emp_details"][1][1] =  "I'm sure the lure in jaipur pours with furore"
>>> print ( json.dumps (json_data, indent=2) )

produces

[
  {
    "add": "dtlz",
    "emp_details": [
      [
        "Shubham",
        "[email protected]",
        "intern"
      ],
      [
        "Gaurav",
        "I'm sure the lure in jaipur pours with furore",
        "the rain in maine falls plainly insane"
      ],
      [
        "Nikhil",
        "[email protected]",
        "Full Time"
      ]
    ]
  }
]

Upvotes: 1

asymptote
asymptote

Reputation: 1402

Here's a more generic solution where outermost json array could have multiple entries (dictionaries):

import json 
with open('test.json', 'r') as file:
  json_data = json.load(file)
  for item in json_data:
    for emp in item['emp_details']:
      if emp[0] in ['Shubham']:
        emp[0] = 'Indra'

with open('zz_smpl.json', 'w') as file:
  json.dump(json_data, file, indent=4)

Upvotes: 0

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

There are 2 problems with your code.

First, the JSON contains an array as the root. Therefore you need to get emp_details property of the first item:

for item in json_data[0]["emp_details"]:

Then in item variable, you need to check the item at index zero:

if item[0] in ['Shubham']:

Here is the full working code:

import json 
with open('smpl.json', 'r') as file:
  json_data = json.load(file)
  for item in json_data[0]["emp_details"]:
    if item[0] in ['Shubham']:
      item[0] = 'Indra'
with open('zz_smpl.json', 'w') as file:
  json.dump(json_data, file, indent=4)

The working repl.it link: https://repl.it/@HarunYlmaz/python-json-write

Upvotes: 0

Related Questions