0

我有一个工作流程,其中一个流程的输出输入到下一个流程。

进程 A 输出一个 JSON。

流程 B 输入需要是 JSON。

但是,由于我将 JSON 作为命令行参数传递,它变成了一个字符串。

下面的这个命令不在我的控制范围内。它是由 Nextflow 自动生成的,所以我需要找到一个解决方案(不必是 JSON),但我需要访问这些值(请记住,这本质上只是一个字符串)

python3.7 typing.py '{'id': '3283', 'code': '1234', 'task': '66128b3b-3440-4f71-9a6b-c788bc9f5d2c'}'

打字.py

def download_this(task_as_string):
    print("Normal")
    print(task_as_string)

    first = json.dumps(task_as_string)
    print("after json.dumps")
    print(first)

    second = json.loads(first)
    print("after json.loads")
    print(second)
    print(type(second))

if __name__ == "__main__":
    download_this(sys.argv[1])

我认为做 ajson.dumps然后 ajson.loads会使其工作,但它不起作用。

输出

Normal
{id: 3283, code: 1234, task: 66128b3b-3440-4f71-9a6b-c788bc9f5d2c}
after json.dumps
"{id: 3283, code: 1234, task: 66128b3b-3440-4f71-9a6b-c788bc9f5d2c}"
after json.loads
{id: 3283, code: 1234, task: 66128b3b-3440-4f71-9a6b-c788bc9f5d2c}
<class 'str'>

如果我这样做,print(second["task"])我会得到一个字符串索引必须是整数

Traceback (most recent call last):
  File "typing.py", line 78, in <module>
    download_this(sys.argv[1])
  File "typing.py", line 55, in download_typed_hla
    print(second["task"])    
TypeError: string indices must be integers

所以它一开始就没有被转换成字典。有什么想法可以解决这个问题吗?

4

1 回答 1

3

几件事:

  1. 您的 JSON 格式不正确。键和值需要用双引号括起来。
  2. 您正在传递 JSON 的字符串化版本。然后在尝试加载它之前进一步对其进行字符串化。直接加载就行了。
def download_this(task_as_string):
    print("Normal")
    print(task_as_string)

    second = json.loads(task_as_string)
    print("after json.loads")
    print(second)
    print(type(second))

download_this('{"id": "3283", "code": "1234", "task": "66128b3b-3440-4f71-9a6b-c788bc9f5d2c"}')

Normal
{"id": "3283", "code": "1234", "task": "66128b3b-3440-4f71-9a6b-c788bc9f5d2c"}
after json.loads
{'id': '3283', 'code': '1234', 'task': '66128b3b-3440-4f71-9a6b-c788bc9f5d2c'}
<class 'dict'>

为了解决您的输入问题,只要您相信来自 Nextflow 的输入符合简单的类字典结构,您可以执行以下操作:

d = dict()
for group in task_as_string.replace('{', '').replace('}', '').split(','):
    l = group.split(':')
    d[l[0].strip()] = l[1].strip()

print(d)
print(type(d))
python3 typing.py '{'id': '3283', 'code': '1234', 'task': '66128b3b-3440-4f71-9a6b-c788bc9f5d2c'}'                      [12:03:11]
{'id': '3283', 'code': '1234', 'task': '66128b3b-3440-4f71-9a6b-c788bc9f5d2c'}
<class 'dict'>

如果来自 Nextflow 的 JSON 更复杂(即带有嵌套和/或列表),那么您将不得不提出更合适的解析机制。

于 2019-10-18T14:33:34.410 回答