Home > Blockchain >  How to rewrite JSON file in gitlab from python
How to rewrite JSON file in gitlab from python

Time:03-26

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(
                private_token='xxxxxxxxx')
gl.auth()
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()
f.write(raw_content)
f.seek(0)
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'))

CodePudding user response:

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)
f.save(...)
  • Related