Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add text to the end of multiple json files

I’m very new to programming so excuse any terrible explanations. Basically I have 1000 json files all that need to have the same text added to the end. Here is an example:

This is what it looks like now:

{"properties": {
    "files": [
      {
        "uri": "image.png",
        "type": "image/png"
      }
    ],
    "category": "image",
    "creators": [
      {
        "address": "wallet address",
        "share": 100
      }
    ]
  }
}

Which I want to look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {"properties": {
    "files": [
      {
        "uri": "image.png",
        "type": "image/png"
      }
    ],
    "category": "image",
    "creators": [
      {
        "address": "wallet address",
        "share": 100
      }
    ]
  },
    "collection": {"name": "collection name"}
}

I’ve tried my best with append and update but it always tells me there is no attribute to append. I also don’t really know what I’m doing.

This will be embarrassing but here is what I tried and failed.

import json

entry= {"collection": {"name": "collection name"}}

for i in range((5)):
  a_file = open("./testjsons/" + str(i) + ".json","r")
  json_obj = json.load(a_file)
  print(json_obj)

json_obj["properties"].append(entry)
a_file = open(str(i) + ".json","w")
json.dump(json_obj,a_file,indent=4)
a_file.close() 
json.dump(a_file, f)

Error code: json_obj["properties"].append(entry)
AttributeError: ‘dict’ object has no attribute ‘append’

>Solution :

you don’t use append() to add to a dictionary. You can either assign to the key to add a single entry, or use .update() to merge dictionaries.

import json

entry= {"collection": {"name": "collection name"}}

for i in range((5)):
    with open("./testjsons/" + str(i) + ".json","r") as a_file:
        a_file = open("./testjsons/" + str(i) + ".json","r")
        json_obj = json.load(a_file)
        print(json_obj)
        
    json_obj["properties"].update(entry)
    with open(str(i) + ".json","w") as a_file:
        json.dump(json_obj,a_file,indent=4)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading