代码之家  ›  专栏  ›  技术社区  ›  Aliaksandra

如何在gitlab中从python重写JSON文件

  •  0
  • Aliaksandra  · 技术社区  · 3 年前

    我在git repo中有一个JSON文件,然后我把它上传到python变量中,用这个变量做一些操作。如何使用此变量在gitlab中更新JSON

    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
    
    

    我知道在Python中我们使用这个命令来更新文件,但我不知道如何在gitlab中更新它

    json.dump(data, open('json_HW.json', 'w'))
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   sytech    3 年前

    使用文件api文件对象。 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')
    

    你可以用 json.dumps 获取新内容的字符串。

    f.content = json.dumps(data)
    f.save(...)