I have a JSON file in git repo, then I upload it into the python variable, do some manipulations with this variable. How can I update JSON in gitlab using this variable

import gitlab
import json
import io

gl = gitlab.Gitlab(
projects = gl.projects.list(owned=True, search='Python')
raw_content = projects[0].files.raw(file_path='8_JSON_Module/json_HW.json', ref='main')
f = io.BytesIO()
data = json.load(f)  # read from the file
... do some manipulations with variable data

I know that in Python we use this command to update the file but I have no idea how to update it in gitlab

json.dump(data, open('json_HW.json', 'w'))

1 Answer 1


Use the files api file object. Reference

f = project.files.get(file_path='README.rst', ref='main')
decoded_content = f.decode()
new_content = modify_content(decoded_content) # you implement this

# update the contents and commit the changes
f.content = new_content
f.save(branch='main', commit_message='Update file')

You can use json.dumps to get a string for the new content.

f.content = json.dumps(data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.