简体   繁体   English

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

[英]How do I format JSON's with multiple of the same keys with python?

I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. 我有一个程序,现在使用powershell脚本和WMI来获取温度和负载等数据。 It outputs the data as a JSON file. 它将数据输出为JSON文件。 Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. 现在让我先说这是我第一次使用JSON并且我对JSON python库不太熟悉。 Here is the code to my program: 这是我的程序的代码:

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)

Now here is the resulting JSON: 现在这里是生成的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
  }
]

As you can see every dictionary in the list has the keys Name , SensorType and Value . 如您所见,列表中的每个字典都有NameSensorTypeValue

What I want to do is make it so that each list has a "label" equal to the Name in each one, so I can call for data from specific entries, one at a time. 我想要做的是使每个列表的“标签”等于每个列表中的Name ,因此我可以一次调用一个特定条目的数据。 Once again, I'm kind of a newbie with JSON and its library so I'm not even sure if this sort of thing is possible. 再一次,我是JSON及其库的新手,所以我甚至不确定这种事情是否可行。 Any help would be greatly appreciated! 任何帮助将不胜感激! Have a good day! 祝你有美好的一天! :) :)

Edit 1: Here is an example, using the first 2, of what I would like the program to be able to output. 编辑1:这是一个例子,使用前两个,我希望程序能够输出。

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

Once again, I dont even know if this is valid JSON but I want it to just do something at least similar to that so I can call, for example, print(data["Memory"]["Value"]) and return, 53.3276978 . 再一次,我甚至不知道这是否是有效的JSON,但我希望它只是做一些至少类似的事情,所以我可以调用,例如, print(data["Memory"]["Value"])并返回, 53.3276978

Edit 2: It did just occur to me that there are some names with multiple sensor types, for example, "CPU Core #1" and "CPU Core #2" both have "Tempurature" , "Load" , and "Clock" . 编辑2:我确实发现有一些具有多种传感器类型的名称,例如, "CPU Core #1""CPU Core #2"都具有"Tempurature""Load""Clock" Using the above example could cause some conflicts so is there a way we could account for that? 使用上面的例子可能会导致一些冲突,那么有什么方法可以解释这个问题?

Assuming you need to keep the values if key already exists: 假设您需要保留值,如果密钥已存在:

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)

will give you 会给你

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

Hope this helps 希望这可以帮助

You can build a new dictionary in the shape you want like this: 你可以像这样建立一个你想要的形状的新字典:

...
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)
...

Result: 结果:

{
    "Memory": {
        "SensorType": "Load",
        "Value": 53.3276978
    },
    "CPU Core #2": {
        "SensorType": "Clock",
        "Value": 2700.00073
    },
    (and so on)
}
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))

Output 产量

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

How about this? 这个怎么样?

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>)

This way, you won't have to del items from the dict s that you load from the file. 这样,您就不必从文件中加载的dict del项目。

You can just replace 你可以替换

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)

with

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用相同的多个键解析JSON? - How do I parse JSON with multiple keys the same? 如何在 JSON 文件中更改多个键 - How can I change multiple keys in a JSON file that has multiple dictionaries which incorporate the same keys but different values with Python 如何使用python重复相同的键集来迭代JSON输出? - How do I use python to iterate JSON output with repeating sets of the same keys? 如何打印出与 Python 中相同值对应的多个键? - How do I print out multiple keys that correspond to the same value in Python? 如何导入在 Python 中有多个密钥的 JSON 文件? - How do I import a JSON file which has multiple keys in Python? 如何在 Python 中循环使用具有多个子键的 JSON 文件? - How do I loop through a JSON file with multiple sub-keys in Python? 如何为多个键分配相同的值 | python - How can i assign multiple keys the same value | python 如何在同一列中转换多种时间格式,然后在 Python 中将其转换为标准时间格式 - How do I convert multiple time formats in the same column to then convert it as a standard time format in Python 如何检查 Python 中是否同时释放 2 个键? - How do I check if 2 keys are released at the same time in Python? 如何在 Python 中使用动态键解析 JSON 文档? - How do I a parse JSON document with dynamic keys in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM