0

I have two files: json and text files.

I would like to replace one of the dictionary value with the value which in the text file.

Let us say, in the text file file.text, I have the following lists. [11, 15, 10].

In the json file, I have the following dictionary.

     "aa": {
            "bb": [
                "25",
                "40",
                "05"
            ],
            "cc": [
                "20"
                ]
                        
        }

I would like to overwrite the cc value with the text file above.

file.json

     "aa": {
            "bb": [
                "25",
                "40",
                "05"
            ],
            "cc": [
                "11", "15", "10"
                ]
                        
        }

I have tried something in Python.

def replace(text_file, json_file):
  tex_file_path = 'C:/Documents/file.txt'
  with open(os.path.join(tex_file_path, text_file), 'r') as f:
    read_text= f.read()

  json_file_path = 'C:/Documents/file.json'
  with open(os.path.join(json_file_path, json_file), 'r') as f:
    read_json = json.load(f)
  text_to_be_replaced = read_json.get('aa')
 

  for value in text_to_be_replaced.items():
    for element in value:
      # statment


I was wondering if someone can really help with this.

4
  • What is the problem? Commented Oct 26, 2021 at 20:09
  • If you see the cc value at the json file, it is already replaced with the value from the text file. I would like to do that. Commented Oct 26, 2021 at 20:12
  • It looks like you're missing a statement to set the value? also, it might be easier to work with strings instead of files. For instance, none of us really have a file.json file, but it might be easier to define the file contents as a multi-line string in code, so it is more easily reproducible for others. Commented Oct 26, 2021 at 20:16
  • Why are you looping through text_to_be_replaced.items()? You only want to replace one item. Commented Oct 26, 2021 at 20:27

2 Answers 2

1

Although you've named it .text, the contents of the file appear to be JSON, so you can use json.load() as well. Then convert the integers in the list to strings and insert it into the desired place in the JSON file.

There's no need to loop over the dictionary items. Just address the specific element you want to replace.

def replace(text_file, json_file):
    tex_file_path = 'C:/Documents'
    with open(os.path.join(tex_file_path, text_file), 'r') as f:
        read_text= json.load(f)
    read_text = list(map(str, read_text))

    json_file_path = 'C:/Documents'
    with open(os.path.join(json_file_path, json_file), 'r') as f:
        read_json = json.load(f)

    read_json["aa"]["cc"] = read_text

    with open(os.path.join(json_file_path, json_file), 'w') as f:
        json.dump(read_json, f)

Also, your XXX_path variables should just be directories, the filename comes from the function parameter.

Sign up to request clarification or add additional context in comments.

5 Comments

I just tried your solution and counter this error TypeError: Object of type TextIOWrapper is not JSON serializable any thought? ```
I had the arguments to json.dump() in the wrong order.
Works but I got the splitted list "[", "1", "1", "1", ",", "5", "1", "0", "]"]}, instead of getting like this"11", "15", "10".
You would get that if you used read_text = f.read() instead of read_text = json.load(f)
That is perfect. Thanks!
1

Here's a simple example using a StringIO to demonstrate reading / writing from a file-like object:

import json
from io import StringIO

json_file_obj = StringIO("""
     {"aa": {
            "bb": [
                "25",
                "40",
                "05"
            ],
            "cc": [
                "20"
                ]

        }
    }
""")

text_file_obj = StringIO("[11, 15, 10]")


def replace(src_file_obj: StringIO, repl_file_obj: StringIO):
    # Load file contents into a Python object
    data = json.load(src_file_obj)

    # Read in txt file contents
    new_cc_value = json.load(repl_file_obj)

    # But now result will be a list of int, here we want a list of string
    new_cc_value = list(map(str, new_cc_value))

    # Replace desired value
    data['aa']['cc'] = new_cc_value

    # Now we write to our file-like object, `src_file_obj`
    # This is to demonstrate replacing the original file contents
    src_file_obj = StringIO()
    json.dump(data, src_file_obj)

    # Seek to the start of the file
    src_file_obj.seek(0)

    return src_file_obj


json_file_obj = replace(json_file_obj, text_file_obj)

print(json_file_obj.read())

Output:

{"aa": {"bb": ["25", "40", "05"], "cc": ["11", "15", "10"]}}

Hint - If you want to write the output to an actual file, you can replace these lines below:

src_file_obj = StringIO()
json.dump(data, src_file_obj)
src_file_obj.seek(0)

With these lines:

with open("file_name.txt", 'w') as out_file:
    json.dump(data, out_file)

4 Comments

You need to get the replacement from a file.
Yes, but the approach should be the same. I'm using a file-like object so it's easily reproducible for others.
ohhh, yeah. I see what you mean now.
@Barmar thanks, I updated with usage of how to read in txt file contents for the replacement value

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.