替换 Jenkins 管道中 json 文件中的字符串值

问题描述 投票:0回答:1

我想用我在 Jenkins 管道中定义的变量替换下面 json 文件中的“version”值。

{
  "name": "new-relic",
  "version": "1.0.0",
  "author": "Tools",
  "summary": "A brief module description",
  "license": "Apache-2.0",
  "source": "https://github.com/DI-Test/puppet-newrelic",
  "dependencies": [

  ],
  "operatingsystem_support": [
    "RedHat based Linux"
  ],
  "requirements": [
    {
      "name": "puppet",
      "version_requirement": ">= 7.24 < 9.0.0"
    }
  ],
  "pdk-version": "3.0.0",
  "template-url": "pdk-default#3.0.0",
  "template-ref": "tags/3.0.0-0-g056e50d"
}

我尝试过 writeJson、writeFile。全部替换文件

writeJSON(  file: 'metadata.json',
                                            json: [
                                                version: "${puppet_module_version}-${BRANCH_NAME}",])

它替换了所有的json内容并只添加一个字符串“version”

jenkins jenkins-pipeline jenkins-groovy jenkins-job-dsl
1个回答
0
投票

这是通过读取包含 JSON 内容的文件并通过

map
返回
readJSON()
,修改与返回的
map
中的键关联的值,然后将
map
写入 JSON 格式
string
来完成的。使用
writeJSON()
:

导出到新文件
Map attributes = readJSON(file: 'file.json')
attributes['version'] = "${puppet_module_version}-${BRANCH_NAME}"
writeJSON(file: 'other_file.json', json: attributes)

这两个 JSON 步骤需要 Pipeline Utility Steps 插件,但假设这些插件已经安装,因为您已经根据问题成功执行了

writeJSON
步骤。

© www.soinside.com 2019 - 2024. All rights reserved.