You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible中正确提取JSON字符串内的ok字段值?

How to Extract the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:30:38