如何使用python使用多个相同的键来格式化JSON?

时间:2018-08-07 19:00:00

标签: python json python-3.x

我有一个程序,现在可以使用Powershell脚本和WMI来获取温度和负载等数据。它将数据输出为JSON文件。现在,让我通过说这是我第一次使用JSON来工作,而我对JSON python库不是很熟悉。这是我程序的代码:

import subprocess
import json

p = subprocess.Popen(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./TestScript\";", "&NSV"], stdout=subprocess.PIPE)
(output, err) = p.communicate()

data = json.loads(output)

for mNull in data:
    del mNull['Scope']
    del mNull['Path']
    del mNull['Options']
    del mNull['ClassPath']
    del mNull['Properties']
    del mNull['SystemProperties']
    del mNull['Qualifiers']
    del mNull['Site']
    del mNull['Container']
    del mNull['PSComputerName']
    del mNull['__GENUS']
    del mNull['__CLASS']
    del mNull['__SUPERCLASS']
    del mNull['__DYNASTY']
    del mNull['__RELPATH']
    del mNull['__PROPERTY_COUNT']
    del mNull['__DERIVATION']
    del mNull['__SERVER']
    del mNull['__NAMESPACE']
    del mNull['__PATH']

fdata = json.dumps(data,indent=2)

print(fdata)

现在这是生成的JSON:

[
  {
    "Name": "Memory",
    "SensorType": "Load",
    "Value": 53.3276978
  },
  {
    "Name": "CPU Core #2",
    "SensorType": "Temperature",
    "Value": 69
  },
  {
    "Name": "Used Space",
    "SensorType": "Load",
    "Value": 93.12801
  },
  {
    "Name": "CPU Core #1",
    "SensorType": "Temperature",
    "Value": 66
  },
  {
    "Name": "CPU DRAM",
    "SensorType": "Power",
    "Value": 1.05141532
  },
  {
    "Name": "CPU Core #2",
    "SensorType": "Load",
    "Value": 60.15625
  },
  {
    "Name": "CPU Package",
    "SensorType": "Power",
    "Value": 15.2162886
  },
  {
    "Name": "Bus Speed",
    "SensorType": "Clock",
    "Value": 100.000031
  },
  {
    "Name": "CPU Total",
    "SensorType": "Load",
    "Value": 57.421875
  },
  {
    "Name": "CPU Package",
    "SensorType": "Temperature",
    "Value": 69
  },
  {
    "Name": "CPU Core #2",
    "SensorType": "Clock",
    "Value": 2700.00073
  },
  {
    "Name": "Temperature",
    "SensorType": "Temperature",
    "Value": 41
  },
  {
    "Name": "Used Memory",
    "SensorType": "Data",
    "Value": 4.215393
  },
  {
    "Name": "Available Memory",
    "SensorType": "Data",
    "Value": 3.68930435
  },
  {
    "Name": "CPU Core #1",
    "SensorType": "Clock",
    "Value": 3100.001
  },
  {
    "Name": "CPU Cores",
    "SensorType": "Power",
    "Value": 13.3746643
  },
  {
    "Name": "CPU Graphics",
    "SensorType": "Power",
    "Value": 0.119861834
  },
  {
    "Name": "CPU Core #1",
    "SensorType": "Load",
    "Value": 54.6875
  }
]

如您所见,列表中的每个词典都有键NameSensorTypeValue

我要做的是使每个列表都具有一个等于每个标签中的Name的“标签”,因此我可以一次从特定条目中调用数据。再一次,我是一个使用JSON及其库的新手,所以我什至不确定这种事情是否可行。任何帮助将不胜感激!祝你有美好的一天! :)

编辑1: 这是一个示例,使用我希望程序能够输出的前2个。

[
  "Memory":{
    "SensorType": "Load",
    "Value": 53.3276978
  },
  "CPU Core #2":{
    "SensorType": "Temperature",
    "Value": 69
  }
]

再一次,我什至不知道这是否是有效的JSON,但我希望它仅执行至少与之类似的操作,以便我可以调用例如print(data["Memory"]["Value"])并返回53.3276978

编辑2: 我确实发现有些名称具有多种传感器类型,例如"CPU Core #1""CPU Core #2"都具有"Tempurature""Load""Clock" 。使用上面的示例可能会导致一些冲突,所以有没有办法解决这个问题?

5 个答案:

答案 0 :(得分:2)

假设密钥已经存在,则需要保留这些值:

                   Connection.Response loginForm = Jsoup.connect("URL" + "/login/").cookies(cookies).method(Connection.Method.GET).execute();

        formData.put("username", "#######");
        formData.put("pwd", "########");
        formData.put("hidden","69");
        formData.put("token", loginForm.parse().select("input#token").first().attr("value"));

        Connection.Response homePage = Jsoup.connect("URL" + "/login/")
                .referrer("URL" + "/login/")
                .followRedirects(true)
                .cookies(cookies)
                .data(formData)
                .method(Connection.Method.POST)
                .execute();

        cookies_2.putAll(homePage.cookies()); // save the cookies, this will be passed on to next request

会给您

import json
data = [
{
    "Name": "Memory",
    "SensorType": "Load",
    "Value": 53.3276978
},
{
    "Name": "CPU Core #2",
    "SensorType": "Temperature",
    "Value": 69
},
{
    "Name": "Used Space",
    "SensorType": "Load",
    "Value": 93.12801
},
{
    "Name": "CPU Core #1",
    "SensorType": "Temperature",
    "Value": 66
},
{
    "Name": "CPU DRAM",
    "SensorType": "Power",
    "Value": 1.05141532
},
{
    "Name": "CPU Core #2",
    "SensorType": "Load",
    "Value": 60.15625
},
{
    "Name": "CPU Package",
    "SensorType": "Power",
    "Value": 15.2162886
},
{
    "Name": "Bus Speed",
    "SensorType": "Clock",
    "Value": 100.000031
},
{
    "Name": "CPU Total",
    "SensorType": "Load",
    "Value": 57.421875
},
{
    "Name": "CPU Package",
    "SensorType": "Temperature",
    "Value": 69
},
{
    "Name": "CPU Core #2",
    "SensorType": "Clock",
    "Value": 2700.00073
},
{
    "Name": "Temperature",
    "SensorType": "Temperature",
    "Value": 41
},
{
    "Name": "Used Memory",
    "SensorType": "Data",
    "Value": 4.215393
},
{
    "Name": "Available Memory",
    "SensorType": "Data",
    "Value": 3.68930435
},
{
    "Name": "CPU Core #1",
    "SensorType": "Clock",
    "Value": 3100.001
},
{
    "Name": "CPU Cores",
    "SensorType": "Power",
    "Value": 13.3746643
},
{
    "Name": "CPU Graphics",
    "SensorType": "Power",
    "Value": 0.119861834
},
{
    "Name": "CPU Core #1",
    "SensorType": "Load",
    "Value": 54.6875
}
]

final_data = {}

for d in data:
    if d['Name'] not in final_data:
        final_data[d['Name']] = list()

    key = d.pop('Name')
    final_data[key].append(temp)


print json.dumps(final_data,indent=4)

希望这会有所帮助

答案 1 :(得分:1)

您可以像这样构建新的字典:

...
data = {
    element["Name"]: {
        key: value for key, value in element.items() if key != "Name"
    }
    for element in json.loads(output)
}
fdata = json.dumps(data, indent=4)
...

结果:

{
    "Memory": {
        "SensorType": "Load",
        "Value": 53.3276978
    },
    "CPU Core #2": {
        "SensorType": "Clock",
        "Value": 2700.00073
    },
    (and so on)
}

答案 2 :(得分:0)

x="""[
  {
    "Name": "Memory 1",
    "SensorType": "Load",
    "Value": 53.3276978
  },
  {
    "Name": "CPU Core #2",
    "SensorType": "Load",
    "Value": 53.3276978
  }]"""

json_obj=json.loads(x)

new_list=[]
for item in json_obj:
    name=item.pop('Name')
    new_list.append({name:item})

print(json.dumps(new_list,indent=4))

输出

[
{
    "Memory 1": {
        "SensorType": "Load", 
        "Value": 53.3276978
    }
}, 
{
    "CPU Core #2": {
        "SensorType": "Load", 
        "Value": 53.3276978
    }
}
]

答案 3 :(得分:0)

怎么样?

import json
orig_list = json.load(<filename>)
new_dict = { l['Name']:{k:v for k,v in l.items() if k!='Name'} for l in orig_list}
json.dumps(new_dict, <filename>)

通过这种方式,您不必从文件中加载的del中的dict个项目中来。

答案 4 :(得分:0)

您可以替换

for mNull in data:
    del mNull['Scope']
    del mNull['Path']
    del mNull['Options']
    del mNull['ClassPath']
    del mNull['Properties']
    del mNull['SystemProperties']
    del mNull['Qualifiers']
    del mNull['Site']
    del mNull['Container']
    del mNull['PSComputerName']
    del mNull['__GENUS']
    del mNull['__CLASS']
    del mNull['__SUPERCLASS']
    del mNull['__DYNASTY']
    del mNull['__RELPATH']
    del mNull['__PROPERTY_COUNT']
    del mNull['__DERIVATION']
    del mNull['__SERVER']
    del mNull['__NAMESPACE']
    del mNull['__PATH']

fdata = json.dumps(data,indent=2)

dontwant=set(['Name', 'PSComputerName', '__RELPATH', '__DYNASTY', '__CLASS', '__PROPERTY_COUNT', 'Site', 'ClassPath', 'SystemProperties', 'Scope', 'Qualifiers', 'Options', '__NAMESPACE', 'Path', '__SUPERCLASS', '__DERIVATION', '__GENUS', '__PATH', 'Container', 'Properties', '__SERVER']) # set of keys to drop
out={} # empty dict
for mNull in data:
    name=mNull['Name']
    out[name]={key:value for key,value in mNull.items() if key not in dontwant} # only copy over items you want

fdata = json.dumps(out,indent=2)