如何阅读一整行,然后只阅读最后五个字符?



我是Python的新手。我想从监控中读取 JSON 文件。文件如下所示

我只需要时间戳、系统名称(如"test-1"(以及来自电源、磁盘和 CPU 的数字。

我的脚本看起来像这样

#!/usr/bin/env python3.3
import os
import json 
with open('test.json', 'r') as f:
distros_dict = json.load(f)
for distro in distros_dict:
print(distro['"power [W]"'])

更新: 如何将它们写入变量?

新示例数据:

[
{
"Area":"CLOUD",
"timestamp":"2019-11-06T00:00:00",
"Systeme":{
"test-4":{
"power [W]":181.05,
"disk [%]":52.28
},
"test-1":{
"power [W]":280.56,
"disk[%]":6.33,
"cpu[%]":0.1
},
"test-2":{
"power [W]":271.84,
"disk[%]":6.52,
"cpu[%]":0.1
},      
"test-8":{
"power [W]":453.56,
"disk[%]":93.63,
"cpu[%]":5.04
}
}
}
]

我想要的输出变量是CPU,电源和磁盘 而不是将它们打印到命令行,我想将它们写在三个变量中

设置字典(json格式,检查它是否在 https://jsonlint.com/上使用正确的格式(

dict = {
"Area": "CLOUD",
"timestamp": "2019-11-06T12:24:25",
"Systeme": {
"test-1": {
"power [W]": 181.05,
"disk [%]": 52.28
},
"test-2": {
"power [W]": 199.67,
"disk [%]": 54.47
},
"test-3": {
"power [W]": 175.68,
"disk [%]": 10.17,
"cpu [%]": 22.43
}}}

将字典加载为 json

import json
x = json.loads(json.dumps(dict))

遍历你的字典[Systeme]并获取你需要打印的所有属性。 我选择使用dict.get("systeme")而不是dict["Systeme"],因为您在 test-3 中缺少 CPU

for line in x["Systeme"]:
power = x.get("Systeme").get(line).get("power [W]", "")
disk = x.get("Systeme").get(line).get("disk [%]", "")
cpu = x.get("Systeme").get(line).get("cpu [%]", "")
print(f"{line} {power} {disk} {cpu}")
power, disk, cpu = "", "", ""

注意:上面的例子是 Python 3.7+,对于早期版本的 Python 需要更改 print 语句:
print("%s %s %s %s"%(line, power, disk, cpu) )

带有多词典的 JSON 文件应该遵循以下格式:

[    
{ 
"Area": "CLOUD",
"timestamp": "2019-11-06T12:24:25",
"Systeme": {
"test-1": {
"power [W]": 181.05,
"disk [%]": 52.28
},
"test-2": {
"power [W]": 199.67,
"disk [%]": 54.47
},
"test-3": {
"power [W]": 175.68,
"disk [%]": 10.17,
"cpu [%]": 22.43
}
}
},
{ 
"Area": "CLOUD",
"timestamp": "2019-11-06T12:24:25",
"Systeme": {
"test-1": {
"power [W]": 181.05,
"disk [%]": 52.28
},
"test-2": {
"power [W]": 199.67,
"disk [%]": 54.47
},
"test-3": {
"power [W]": 175.68,
"disk [%]": 10.17,
"cpu [%]": 22.43
}
}
}
]

您只需要将每个字典中的值合并到一个字符串中即可获得结果:

with open('test.json', 'r') as f:
distros_dict = json.load(f)
test_keys = ['power [W]', 'disk [%]', 'cpu [%]']
for distro in distros_dict:
for key, value in distro['Systeme'].items():
output_list =[]
output_list.append(key)
for single_system_key, single_system_value in distro['Systeme'][key].items():
if single_system_key in test_keys:
output_list.append(single_system_value)
print(' - '.join(str(e) for e in output_list))

最终输出让您:

test-1 - 181.05 - 52.28
test-2 - 199.67 - 54.47
test-3 - 175.68 - 10.17 - 22.43
test-1 - 181.05 - 52.28
test-2 - 199.67 - 54.47
test-3 - 175.68 - 10.17 - 22.43

您可以使用元组列表来存储变量。下面是如何执行此操作的示例。

import json
import sys
data = None
with open('test.json', 'r') as file:
data = json.load(file)
# since we are dealing with input from another source, we should validate it every step of the way
# check if there was no data in the file
if not data:
sys.exit(0)

variables = []  # this list would contain tuples. The tuple would contain system name, cpu, power, and disk. Any missing data would be set as None
for distro in data:
if 'Systeme' not in distro:  # we verify this attribute exists
continue
for system_name, system in distro['Systeme'].items():
variables.append( 
(system_name, system.get('cpu[%]'), system.get('power [W]'), system.get('disk[%]'))
)
# now that we have them stored inside the 'variables' list, we can print them to verify that they are stored.
for system_name, cpu, power, disk in variables:
print(system_name, cpu, power, disk)
# do other stuff with these variables here if you want.

你可以尝试这种方法。 您将需要为其安装熊猫

点安装熊猫

import json
import pandas as pd
data = json.load(open('data.json'))  // asuming your data is in data.json

new_json=[]
for rec in data:
new_doc = {}
for key in rec:
if type(rec[key]) is str:
new_doc[key] = rec[key]
else:
for key1 in rec[key]:
if type(rec[key][key1]) is str:
new_doc[key+'_'+key1] = rec[key][key1]
else:
for key2 in rec[key][key1]:
if type(rec[key][key1][key2]) in [str,float,int]:
new_doc[key+'_'+key1+'_'+key2] = rec[key][key1][key2]
else:
print("don't support more nested json")
new_json.append(new_doc)
data = pd.DataFrame(new_json)
data.head()  //peak into your new data structure][1]][1]

现在,您将拥有一个格式良好的表结构,并且可以对其进行任何查询。 因此,要获得所有类型 1 的幂和时间戳,只需执行

data[['Systeme_test-1_power [W]','timestamp']]

我们可以从这里非常轻松地进行许多其他类型的查询和图形绘制。 阅读熊猫文档了解更多信息,如有疑问,请发表评论

最新更新