2

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!!!

3
  • could you edit the post with your expectation would be very helpful to understand your intent Commented Feb 6, 2020 at 7:10
  • Could you elaborate on the troubles you are having? Is there an error, wrong result, etc? Commented Feb 6, 2020 at 7: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", "[email protected]", "intern" ], [ "Gaurav", "[email protected]", "developer" ], [ "Nikheel", "[email protected]", "Full Time" ] ] } ] Commented Feb 6, 2020 at 8:06

3 Answers 3

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    "[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"
      ]
    ]
  }
]
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

2 Comments

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.
You can have a look at these SO threads: 1, 2, 3
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)

1 Comment

Can you give me some extra advice for replacing certain keywords(not the entire word) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.