简体   繁体   中英

How to print value in nested json format using python

Here is my code :

if m.namespace in metric_config.keys():
 for d in m.dimensions.keys():
  if d == metric_config[m.namespace]["dimension"]:
    if m.name in metric_config[m.namespace]["metrics"].keys():
      if len(metric_config[m.namespace]["metrics"][m.name]) > 0:
        metric["Namespace"] = m.namespace
        metric["MetricName"] = m.name
        dimension["Value"] = m.dimensions[d][0]
        metric["Statistics"] = metric_config[m.namespace]["metrics"][m.name][0]

if metric != {} and dimension != {}:
  cwatch_config["metrics"].append(metric)
  cwatch_config['Dimensions'].append(dimension)

This code is not printing dimension in metric column and I want to print it in required format as below mention.

"metricsConfig": {
  "metrics": [
  {
    "Namespace": "AWS/RDS",
    "Statistics": [
      "Average"
    ],
    "Dimensions": [
      {
        "Name": "DBInstanceIdentifier",
      }
    ]
  }
],

}

If you have parsed your data into a JSON object j , then you can convert it to a JSON string using json.dumps(j) . The optional indent parameter allows you to specify how nested elements should be formatted:

>>> print(json.dumps(j, indent=2))
{
  "metricsConfig": {
    "metrics": [
      {
        "Namespace": "AWS/RDS",
        "Statistics": [
          "Average"
        ],
        "Dimensions": [
          {
            "Name": "DBInstanceIdentifier"
          }
        ]
      }
    ]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM