【问题标题】:Generate file and replace strings in template file in the generated files在生成的文件中生成文件并替换模板文件中的字符串
【发布时间】:2018-09-15 11:24:06
【问题描述】:

我有一个 JSON 文件:

{
    "header": {
        "uuid": "c578592a-a751-4993-9060-53f488597e59",
        "timestamp": 1522938800,
        "productionDateTime": "2018-04-05T14:33:20.000+00:00",
        "producers": {
            "operator": null,
            "application": {
                "com.example": {
                    "id": {
                        "string": "1"
                    },
                    "name": {
                        "string": "Test"
                    }
                }
            },
            "station": null,
            "equipment": null,
            "partner": null,
            "flow": null
        },
        "correlationContext": {
            "array": [{
                "correlationId": "98440498-3104-479e-9c99-f4449ba8f4b6",
                "correlationDateTime": {
                    "string": "2018-04-05T14:30:39.000+00:00"
                }
            }]
        }
    },
}

我想创建 n 个复制 JSON 文件但具有随机相关 ID 和相关日期时间的文件。

您有什么建议或建议吗?非常感谢!

【问题讨论】:

  • 你的系统里有python吗?
  • 是的,你能告诉我更多细节吗?
  • @Itqbx,我提供了一个解决方案。试试看。它对我有用。
  • 随机“correlationDateTime”是什么意思?从现在到宇宙大爆炸?现在和 Unix 时代的开始?

标签: json bash sed jq auto-generate


【解决方案1】:

使用jq 并将生成适当的随机值作为练习留给读者:

$ jq --arg cid "foo" --arg cdt "bar" '
    .header.correlationContext.array[0]={
        correlationId: $cid,
        correlationDateTime: {string: $cdt}
     }' tmp.json

【讨论】:

    【解决方案2】:

    给你:-

    #!/bin/bash
    alias uid="python -c 'import sys,uuid; sys.stdout.write(uuid.uuid4().hex)' | pbcopy && pbpaste && echo"
    dt=$(date "+%Y%m%d-%H%M%S")
    # For above two values I am leaving with you. If you have best option please go for it
    i=0
    while [ $i -le 20 ]
    do
      sed  "/correlationId/s/98440498-3104-479e-9c99-f4449ba8f4b6/"$uid"/;s/2018-04-05T14:30:39.000+00:00/"$dt"/" yourJsonFile.json > testcase$i.json
      i=$((i+1))
    done
    

    【讨论】:

    • 非常感谢您的回答。但是,行 alias uid="python -c 'import sys,uuid; sys.stdout.write(uuid.uuid4().hex)' | pbcopy && pbpaste && echo" 对我不起作用 -> 行相关性 ID在生成的文件中是空的 ("correlationId": "",) :(
    • @itqbx,只需找到生成correlationId 的解决方案并更改该行即可。这将解决您的问题。休息一切都很好,我已经测试过了。您可以简单地对其进行测试并添加行 uid="123-456-789-1122-3344-5566" 并检查。
    • 是的,使用 uuidgen 命令可以完美运行。感谢您的跟进!
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    相关资源
    最近更新 更多