Skip to content

Instantly share code, notes, and snippets.

@gardar
Created June 13, 2022 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gardar/8e17f6bd69f48948ec7701a6f867a210 to your computer and use it in GitHub Desktop.
Save gardar/8e17f6bd69f48948ec7701a6f867a210 to your computer and use it in GitHub Desktop.
Ansible playbook to convert ruby hash to json dict
- name: convert ruby hash to json
  debug:
    msg: "{{ ruby_hash |
          regex_replace('([{,]\\s*):([^>\\s]+)\\s*=>', '\\1\"\\2\"=>') |
          regex_replace('([{,]\\s*)([0-9]+\\.?[0-9]*)\\s*=>', '\\1\"\\2\"=>') |
          regex_replace('([{,]\\s*)(\".+?\"\\|[0-9]+\\.?[0-9]*)\\s*=>\\s*:([^,}\\s]+\\s*)', '\\1\\2=>\"\\3\"') |
          regex_replace('([\\[,]\\s*):([^,\\]\\s]+)', '\\1\"\\2\"') |
          regex_replace('=>nil', '=>null') |
          regex_replace('([{,]\\s*)(\".+?\"|[0-9]+\\.?[0-9]*)\\s*=>', '\\1\\2:') |
          regex_replace('([{,]\\s*)''(.+?)''\\s*=>', '\\1\"\\2\":')
          }}"

  vars:
    ruby_hash: "{:data=>{:color=>\"blue\", :number=>\"eleventeen\"}, :metadata=>{:created_time=>\"2022-05-13T14:42:18.949064761Z\", :custom_metadata=>nil, :deletion_time=>\"\", :destroyed=>false, :version=>1}}"
TASK [convert ruby hash to json] ************************************
ok: [localhost] => {
    "msg": {
        "data": {
            "color": "blue",
            "number": "eleventeen"
        },
        "metadata": {
            "created_time": "2022-05-13T14:42:18.949064761Z",
            "custom_metadata": null,
            "deletion_time": "",
            "destroyed": false,
            "version": 1
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment