如何在Ansible中正确提取JSON字符串内的ok字段值?
ok Field from MongoDB Cluster Status in Ansible Let's break down why your current approach isn't working and fix it step by step.
The Root Cause
Looking at your debug output, the content of rv_cluster_status.stdout isn't a raw JSON object—it's a JSON-encoded string that wraps the actual cluster status JSON.
Specifically, the output starts and ends with double quotes, and all internal quotes are escaped (e.g., \"set\" instead of "set"). When you try to run from_json directly on this, Ansible parses it as a plain string (the escaped JSON text) instead of a JSON object, hence the decoding error.
Fixes
You have two reliable ways to resolve this:
Option 1: Double from_json Parsing
The first from_json will strip the outer quotes and unescape the internal characters (turning \" back into ", \n into actual newlines, etc.), giving you a valid JSON text string. The second from_json then parses this string into a proper JSON object, allowing you to access the .ok field.
- name: Extract the 'ok' field from MongoDB cluster status debug: msg: "{{ (rv_cluster_status.stdout | from_json | from_json).ok }}"
Option 2: Remove Outer Quotes with Regex
Use regex_replace to strip the leading and trailing double quotes from the stdout content first, then parse the resulting valid JSON text into an object:
- name: Extract the 'ok' field from MongoDB cluster status debug: msg: "{{ (rv_cluster_status.stdout | regex_replace('^\"|\"$', '') | from_json).ok }}"
Either approach will correctly extract the value 1 from the ok field in your cluster status output.
内容的提问来源于stack exchange,提问作者pkaramol

