【问题标题】:srting to dictionary or json after subprocess check_output子进程 check_output 后​​的字符串到字典或 json
【发布时间】:2017-08-07 14:26:20
【问题描述】:

我正在使用subprocess check_output,并且我有一个输出字符串可以使用:

import subprocess
import sys

command = 'some command'
a = subprocess.check_output(command,shell=True).decode(sys.stdout.encoding)

print(repr(a))

我正在接收这个字符串作为输出。

[ { id: 'id_number1',\n    status: 'running'},\n { id: 'id_number2',\n    status: 'running'}]\n

以字符串为例,在实际字符串中每个对象有 20+ 个 key ,对象{.. }可能是 1 或 10

1 个对象的真实字符串

[ { id: '6b2708c992d1b469f32c9d1143ed9a758a20ef57',\n    status: 'running',\n    configPath: 'D:\\\\Sre\\\\',\n    uptime: '2h 4m 35s',\n    restarts: 0,\n    peers: 172,\n    offers: 417,\n    dataReceivedCount: 6,\n    delta: '-12ms',\n    port: 4232,\n    stor: '25',\n    percent: '1' } ]\n

我想将此字符串转换为 Python 3 字典或 json。

【问题讨论】:

  • from ast import literal_eval 然后literal_eval(a) - 这行得通吗?
  • 我试过错误ValueError: malformed node or string: <_ast.Name object at 0x037513D0>
  • 你能发布更长的输出字符串吗?
  • 添加真正的大字符串

标签: python string dictionary subprocess


【解决方案1】:

即使不那么优雅,试试:

string = "[ { id: 'id_number1',\n    status: 'running'},\n { id: 'id_number2',\n    status: 'running'}]\n"

dict_subproc = {}
listfromstr = string.replace("[", "").replace(" ", "").replace(",", "").replace("[", "").replace("{", "").replace("}", "").replace("]", "").split("\n")

lst =  [j for i in listfromstr for j in i.split(":")]

for i, itm in enumerate(lst):
    if itm == "id":
        dict_subproc[lst[i+1]] = lst[i+3]

编辑

词典列表:

string = "[ { id: 'id_number1',\n    status: 'running'},\n { id: 'id_number2',\n    status: 'running'}]\n"

list_subproc = []
listfromstr = string.replace("[", "").replace(" ", "").replace(",", "").replace("[", "").replace("{", "").replace("}", "").replace("]", "").split("\n")

lst =  [j for i in listfromstr for j in i.split(":")]

for i, itm in enumerate(lst):
    if itm == "id":
        list_subproc.append({itm : lst[i+1], lst[i+2] : lst[i+3]})

【讨论】:

  • 我收到了一些错误 `{"'id_number'": "'running'"}` 但缺少键 idstatus
  • 您想要字典列表[{id = id1, status=running}, {id = id2, status=running}] 还是字典{id1: running, id2: running}
  • 我需要 [{u'status': u'running', u'id': u'id_number1'}, {u'status': u'running', u'id': u 'id_number2'}]
【解决方案2】:

我的想法是将您的字符串转换为符合 JSON 的格式。

import json

s = "[ { id: 'id_number1',\n    status: 'running'},\n { id: 'id_number2',\n    status: 'running'}]\n"

s=s.replace(' ', '')
s=s.replace('\n', '')
s=s.replace('status:', '"status":')
s=s.replace('id:', '"id":')
s=s.replace('\'', '\"')

d = json.loads(s)
print d

它会输出:

[{u'status': u'running', u'id': u'id_number1'}, {u'status': u'running', u'id': u'id_number2'}]

作为 python 的字典列表。

【讨论】:

  • 我觉得这个太具体了,试着写一个更笼统的答案
  • 这确实太具体了,但如果字符串格式严格按照作者帖子中提供的格式,这是一种实现它的方法。为了写出更通用的答案,我们需要作者提供更通用的字符串格式,因为我们可以想象任何我们想要的。
  • 有超过 2 个键(我仅在示例中显示 2 个键)几乎 20 多个键我认为使用 x20 relpace 不好
  • 绝对不是。您应该使用正则表达式来匹配每个键。提示:每个键都以 ':' 结尾。
【解决方案3】:

这行得通。

a = "[ { id: 'id_number1',\n    status: 'running'},\n { id: 'id_number2',\n    status: 'running'}]\n"


a = a[1:-2].replace("    ", "").split("\n")

listone = ["".join(a[:2]),
           "".join(a[2:])]

lista =[eval(listone[0][:-1].replace("{", "{'").replace(":", "':").replace(",", ",'")),
        eval(listone[1].replace("{", "{'").replace(":", "':").replace(",", ",'"))]

输出:

>>> lista
[{'status': 'running', ' id': 'id_number1'}, {'status': 'running', ' id': 'id_number2'}]

【讨论】:

    【解决方案4】:

    我已经找到了解决办法,可能不是很好,但是..

    import re
    import subprocess
    
    a = subprocess.check_output(command,shell=True).decode('utf-8')
    
    #using replace to isolate keys and values
    new = a.replace('{ ', ';').replace(' }',', }'). replace('\n    ', ';').replace(': ',':@')
    
    findkeys = re.compile(r';(\S*?):')
    keys_list = findkeys.findall(new)
    findvalue= re.compile(r'@(.*?),')
    values_list = findvalue.findall(new)
    info = dict(zip(keys_list, values_list))
    print(info)
    

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多