如何从json获取对象

时间:2019-07-19 11:27:19

标签: python json boto3

我想从Json对象获取一个对象块。

这是Json对象。我只想获取单个块。

{
"widgets": [

    {
        "type": "metric",
        "x": 0,
        "y": 0,
        "width": 12,
        "height": 6,
        "properties": {
            "metrics": [
                [ "AWS/EC2", "NetworkPacketsIn", "InstanceId", "16" ]
            ],
            "period": 300,
            "region": "ap-south-1",
            "stat": "Average",
            "title": "17"
        }
    },
    {
        "type": "metric",
        "x": 0,
        "y": 0,
        "width": 12,
        "height": 6,
        "properties": {
            "metrics": [
                [ "AWS/EC2", "NetworkPacketsIn", "InstanceId", "16" ]
            ],
            "period": 300,
            "region": "ap-south-1",
            "stat": "Average",
            "title": "17"
        }
    }

]
}

这是我尝试过的代码。但是没有运气。你能告诉我在哪里修改吗?

import boto3
import json    
# Create CloudWatch client
client = boto3.client('cloudwatch')    
response = client.get_dashboard(DashboardName='ritesh')    
body =response['DashboardBody']
r = json.dumps(body)
loaded_r = json.loads(r)
print(loaded_r[1])

我只希望提取此部分

预期产量

{
        "type": "metric",
        "x": 0,
        "y": 0,
        "width": 12,
        "height": 6,
        "properties": {
            "metrics": [
                [ "AWS/EC2", "NetworkPacketsIn", "InstanceId", "16" ]
            ],
            "period": 300,
            "region": "ap-south-1",
            "stat": "Average",
            "title": "17"
  }

5 个答案:

答案 0 :(得分:0)

首先,您需要使用json.load()而不是json.loads(),因为后者返回一个字符串,这就是为什么在打印单个字符时会得到一个字符的原因。

第二,删除r = json.dumps(body)行。

然后您的json只有一个字典widgets,其中包含字典列表。 您的印刷品应指定该父词典,以便能够获取所需的对象。替换为该打印件:

print(loaded_r['widgets'][0])

答案 1 :(得分:0)

改为使用

print(loaded_r['widgets'][1])

由于您的JSON对象被解释为字典,因此将widgets作为键,将list作为值,您需要第二个索引。
另外,这个dumps代码块似乎是多余的,我认为这足够了。

loaded_r = json.loads(body)

摆脱

r = json.dumps(body)

答案 2 :(得分:0)

假设您的json对象存储在文件中,假设test.json。 使用json模块将JSON字符串转换为字典结构。然后提取所需的部分。

if "test.json": # check the file exsists
    with open("test.json", 'r') as f:
        datastore = json.load(f)
datastore["widgets"][1]

答案 3 :(得分:0)

您的代码应该是这样的

import boto3
import json    
# Create CloudWatch client
client = boto3.client('cloudwatch')    
response = client.get_dashboard(DashboardName='ritesh')    
body =response['DashboardBody']
loaded_r = json.loads(body)
print(loaded_r['widgets'][1])
  1. 您不需要r = json.dumps(body)
  2. json.loads()将响应转换为dict,您可以随同浏览
  3. 您可以通过致电type(json.load(body))
  4. 进行检查

答案 4 :(得分:0)

下面是我用来构建仪表板和更新云监视仪表板而不删除先前小部件的代码。

以下代码  1)接受excel文件中的指标。  2)拉有关仪表板中现有窗口小部件的信息  3)附加所需的jason脚本,以添加excel中指定的新窗口小部件  4)将新的json脚本追加到现有的json脚本  5)更新仪表板。

import boto3
import json
import csv
# Create CloudWatch client
client = boto3.client('cloudwatch')

response = client.get_dashboard(
  DashboardName='my-dashboard'
)

#print(response['DashboardBody'])

file = open("sample.csv","r")
numline = len(file.readlines())

name="ritesh"
obj="ritesh-test"

count =0
file = open("sample.csv","r")
reader = csv.reader(file)


first = 0
for line in reader:
    if (first == 0 ):
         first = first +1
         continue

    No_Dash="""
    {
        "type": "metric",
        "x": 0,
        "y": 0,
        "width": 12,
        "height": 6,
        "properties": {
            "metrics": [
                [ "AWS/EC2", "NetworkPacketsIn", "InstanceId", "%s" ]
            ],
            "period": 300,
            "region": "ap-south-1",
            "stat": "Average",
            "title": "%s"
        }
    }"""%(line[0],line[0])

    if count == 0:
        Dash = No_Dash
        count = count + 1
    else:
         Dash=Dash+","+No_Dash


body =response['DashboardBody']
response = client.get_dashboard(DashboardName='ritesh')

#body =json.dumps(response['DashboardBody'])

loaded_r = json.loads(response['DashboardBody'])
for i in range(len(loaded_r["widgets"])):
    Dash = json.dumps(loaded_r["widgets"][i]) + "," + Dash

print(Dash)


test = """{
"widgets": [
     %s

]
}"""%(Dash)



print(test)

response = client.put_dashboard(
    DashboardName= name,
    DashboardBody= test


)