JSON 到字符串到 JSON Python

JSON to String to JSON Python

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

进程A输出一个JSON.

进程 B 输入需要 JSON。

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

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

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

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

我以为先做一个 json.dumps 然后再做一个 json.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"]) 我得到一个字符串 indices must be integers

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

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

几件事:

  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 更复杂(即嵌套 and/or 列表),那么您将不得不想出更合适的解析机制。