2

smpl.json file:

[ 
   { 
      "add":"dtlz",
      "emp_details":[ 
         [ 
            "Shubham",
            "ksing.shubh@gmail.com",
            "intern"
         ],
         [ 
            "Gaurav",
            "gaurav.singh@cobol.in",
            "developer"
         ],
         [ 
            "Nikhil",
            "nikhil@geeksforgeeks.org",
            "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!!!

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
Rubin
  • 31
  • 6
  • could you edit the post with your expectation would be very helpful to understand your intent – jaswanth Feb 06 '20 at 07:10
  • Could you elaborate on the troubles you are having? Is there an error, wrong result, etc? – Andreas Feb 06 '20 at 07:14
  • I want to search certain words in the arrays of the json file and replace those words with new one. For instance, search "il" and replace it with "eel". So that it will look like this: [ { "add":"dtlz", "emp_details":[ [ "Shubham", "ksing.shubh@gmaeel.com", "intern" ], [ "Gaurav", "gaurav.singh@cobol.in", "developer" ], [ "Nikheel", "nikheel@geeksforgeeks.org", "Full Time" ] ] } ] – Rubin Feb 06 '20 at 08:06

3 Answers3

1

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    "ksing.shubh@gmail.com",\n    "intern"\n  ],\n  [\n    "Gaurav",\n    "gaurav.singh@cobol.in",\n    "developer"\n  ],\n  [\n    "Nikhil",\n    "nikhil@geeksforgeeks.org",\n    "Full Time"\n  ]\n]'

and

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

produces

[
  [
    "Shubham",
    "ksing.shubh@gmail.com",
    "intern"
  ],
  [
    "Gaurav",
    "gaurav.singh@cobol.in",
    "developer"
  ],
  [
    "Nikhil",
    "nikhil@geeksforgeeks.org",
    "Full Time"
  ]
]

Therefore,

>>> json_data[0]["emp_details"][1]
['Gaurav', 'gaurav.singh@cobol.in', '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",
        "ksing.shubh@gmail.com",
        "intern"
      ],
      [
        "Gaurav",
        "I'm sure the lure in jaipur pours with furore",
        "the rain in maine falls plainly insane"
      ],
      [
        "Nikhil",
        "nikhil@geeksforgeeks.org",
        "Full Time"
      ]
    ]
  }
]
Blessed Geek
  • 21,058
  • 23
  • 106
  • 176
  • thanks for the info. can you suggest me some more about replacing certain letters of the array? Like how to replace "il" of all arrays to "eel". It would be great help! Looking forward for the answer. – Rubin Feb 06 '20 at 08:32
0

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

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • Thanks a lot!!! Can I ask one more? How can I search certain words int the entire file like "il" and change it to "eel"? Is there any way, we can do that? I'm really sorry but I am so curious to know. – Rubin Feb 06 '20 at 07:39
  • You can have a look at these SO threads: [1](https://stackoverflow.com/a/53078032/1331040), [2](https://stackoverflow.com/a/4944929/1331040), [3](https://stackoverflow.com/a/20593644/1331040) – Harun Yilmaz Feb 06 '20 at 07:44
0

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)
asymptote
  • 1,133
  • 8
  • 15
  • Can you give me some extra advice for replacing certain keywords(not the entire word) ? – Rubin Feb 06 '20 at 08:20