Prasta Maha
Prasta Maha

Reputation: 75

Parse json to custom format

I have a file with json format like this

[
  {
    "name": "enable_replica",
    "value": "on"
  },
  {
    "name": "enable_production",
    "value": "on"
  },
  {
    "name": "max_replica",
    "value": "10"
  },
  {
    "name": "min_replica",
    "value": "5"
  }
]

I need to format it to string so it will look like this

enable_replica=on,enable_production=on,max_replica=10,min_replica=5

I tried using json_query but it still does not work

- command: "cat ~/config.json"
  register: config

- set_fact:
    database_flags: "{{ config.stdout | from_json | json_query('[*]') | join(',') }}"

Does anyone have an idea?

Upvotes: 1

Views: 48

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39119

You can achieve the reformatting solely with JMESPath.
You would just have to leverage the possibilities of the join function.

So, given the fact:

- set_fact:
    database_flags: "{{
        config.stdout
        | from_json
        | json_query('[].join(`=`, [name, value]) | join(`,`, @)')
      }}"

A debug on database_flags would yield you:

ok: [localhost] => 
  database_flags: enable_replica=on,enable_production=on,max_replica=10,min_replica=5

Upvotes: 1

Related Questions