YuriyF
YuriyF

Reputation: 47

Insert multi-line JSON into YAML

Have a ConfigMap.yaml file that looks like this:

apiVersion: v1
kind: ConfigMap
metadata:
  name: someCF
data:
  appsettings.k8s.json: |
   {
    "Logging": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
       }
     }
   }

Also have another JSON file named JSON1 that I need to put into data.appsettings.k8s.json:

    {
    "Logging": {
      "LogLevel": {
        "Default": "Full",
        "Microsoft": "Error",
        "Microsoft.Hosting.Lifetime": "Information"
       }
     }
   }

How to change JSON in data.appsettings.k8s.json so it will look like this:

apiVersion: v1
kind: ConfigMap
metadata:
  name: someCF
data:
  appsettings.k8s.json: |
    {
      "Logging": {
        "LogLevel": {
          "Default": "Full",
          "Microsoft": "Error",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      }
    }

Upvotes: 2

Views: 2203

Answers (2)

Mike Farah
Mike Farah

Reputation: 2574

Note that you can also load the file as a string direct like this:

yq '.data."appsettings.k8s.json" = loadstr("json_file")' yaml

disclaimer: I wrote yq

Upvotes: 3

Inian
Inian

Reputation: 85550

You can pretty-print the JSON file and pass that as an argument to yq. Since mikefarah/yq allows you to update YAML multi-line, you could just do.

The style for the appsettings.k8s.json is already at literal, so it doesn't have to be modified

JSON="$(yq -o=json json_file)" yq '.data."appsettings.k8s.json" = strenv(JSON)' yaml

Use the -i or --inplace flag to update the file inplace. Tested on version 4.25.3

Upvotes: 2

Related Questions