使用 shell 将 JSON 字符串转换为字典,无需转义
Transform JSON String to Dictionary using shell without escape
我正在使用一个输入参数从 shell 调用 python 脚本。
python main.py """{"key1":"value1", "key2":"value2"}"""
所有键和值都是字符串。进入 python 后,我想将 JSON 字符串转换为字典,因此我可以使用键访问这些值。
我尝试了以下方法
import json
import sys
dict_in = json.loads(sys.argv[1])
但是 dict_in
会变成这样的字符串 {key1:value1, key2:value2}
所以看来我需要找到一种方法将带引号的字符串从 shell 传递到 python。我不能使用转义字符,因为字符串是由不同的程序提供的。
有什么优雅的方法可以解决这个问题吗?
不确定您传递的内容是否重要,但您可以传递以下内容并获得所需的输出:
"{\"key1\":\"value1\", \"key2\":\"value2\"}"
或
'{"key1":"value1", "key2":"value2"}'
这是代码和输出:
$cat json_convert.py
import json
import sys
dict_in = json.loads(sys.argv[1])
print (dict_in)
$ python json_convert.py '{"key1":"value1", "key2":"value2"}'
{'key1': 'value1', 'key2': 'value2'}
此外,如果您询问 bash
,您传递的内容 """{"key1":"value1", "key2":"value2"}"""
转换为 "" + "{" + key1 + ":" + value1 + ", " + + key2 + ":" + value2 + "}" + ""
,如果您使用 python
的参数调用该函数本身你会得到想要的结果。
所以真的要看你怎么称呼它了。
如果您仍然喜欢报价,请继续并通过 """{"'"key1"'":"'"value1"'", "'"key2"'":"'"value2"'"}"""
以获得所需的结果:)
我找到了一个可以处理这种情况的 python 2 模块。
假设你有这个字符串:
>>> str = '{foo: bar, id: 23}'
然后你可以使用yaml
如下:
>>> import yaml
>>> dict = yaml.load(str)
>>> dict
{'foo': 'bar', 'id': 23}
>>> dict['foo']
'bar'
现在您已经拥有了所需的东西。
更多信息(以及 python 3 支持等)可在此处找到:https://pyyaml.org/wiki/PyYAMLDocumentation
使用其中之一:
$ your_other_program | python main.py
将其他程序的输出发送到 python,或使用 base64.b64encode(json.dumps(blah))
,您将获得像
这样的漂亮代码
'eyJtQXV0b21hdGljVGVzdExpc3QiOiBbeyJtWSI6IDguMTE0MTA1LCAibU5hbWUiOiAiYWNjZWxlcmF0b3JFbnRpdHkiLCAibVRlc3RTdGF0dXMiOiB0cnVlLCAibVgiOiAzLjgwNDM1MTgsICJtWiI6IC0zLjM4OTU3MjF9LCB7Im1OYW1lIjogImJhcm9tZXRlckVudGl0eSIsICJtVmFsdWUiOiAwLCAibVRlc3RTdGF0dXMiOiBmYWxzZX1dLCAibUF1dG9tYXRpY1Rlc3RDb21wbGV0ZWQiOiB0cnVlfQ=='
放入命令行,然后将其从 base64
解码回 JSON。
或者,更好的是,使用:
$ your_other_program >output_file.tmp
$ python main.py < output_file.tmp
$ rm output_file.tmp
好的,这是我的测试脚本:
print("original sys.argv output\n" + (sys.argv[1]))
string_temp=(yaml.load(sys.argv[1]))
print ("first transformation\n" +string_temp)
string_temp=string_temp.replace(":",": ")
dict_in=yaml.load(string_temp)
print("This is the dictionary")
print(dict_in)
这是我在控制台中输入的内容
python test_script.py """{foo:bar, id:23}"""
这是输出
original sys.argv output
"{foo:bar, id:23}"
first transformation
{foo:bar, id:23}
This is the dictionary
{'foo': 'bar', 'id': 23}
这仅在我使用三重引号 (""") 时有效。如果我使用 (") 或 (') 定义输入字符串,我会收到错误消息。
或者可以从 sys.argv[1]
中删除 (")
print("original sys.argv output\n" + (sys.argv[1]))
string_temp=(sys.argv[1])[1:-1]
print ("first transformation\n" +string_temp)
string_temp=string_temp.replace(":",": ")
dict_in=yaml.load(string_temp)
print("This is the dictionary")
print(dict_in)
我正在使用一个输入参数从 shell 调用 python 脚本。
python main.py """{"key1":"value1", "key2":"value2"}"""
所有键和值都是字符串。进入 python 后,我想将 JSON 字符串转换为字典,因此我可以使用键访问这些值。
我尝试了以下方法
import json
import sys
dict_in = json.loads(sys.argv[1])
但是 dict_in
会变成这样的字符串 {key1:value1, key2:value2}
所以看来我需要找到一种方法将带引号的字符串从 shell 传递到 python。我不能使用转义字符,因为字符串是由不同的程序提供的。
有什么优雅的方法可以解决这个问题吗?
不确定您传递的内容是否重要,但您可以传递以下内容并获得所需的输出:
"{\"key1\":\"value1\", \"key2\":\"value2\"}"
或
'{"key1":"value1", "key2":"value2"}'
这是代码和输出:
$cat json_convert.py
import json
import sys
dict_in = json.loads(sys.argv[1])
print (dict_in)
$ python json_convert.py '{"key1":"value1", "key2":"value2"}'
{'key1': 'value1', 'key2': 'value2'}
此外,如果您询问 bash
,您传递的内容 """{"key1":"value1", "key2":"value2"}"""
转换为 "" + "{" + key1 + ":" + value1 + ", " + + key2 + ":" + value2 + "}" + ""
,如果您使用 python
的参数调用该函数本身你会得到想要的结果。
所以真的要看你怎么称呼它了。
如果您仍然喜欢报价,请继续并通过 """{"'"key1"'":"'"value1"'", "'"key2"'":"'"value2"'"}"""
以获得所需的结果:)
我找到了一个可以处理这种情况的 python 2 模块。
假设你有这个字符串:
>>> str = '{foo: bar, id: 23}'
然后你可以使用yaml
如下:
>>> import yaml
>>> dict = yaml.load(str)
>>> dict
{'foo': 'bar', 'id': 23}
>>> dict['foo']
'bar'
现在您已经拥有了所需的东西。
更多信息(以及 python 3 支持等)可在此处找到:https://pyyaml.org/wiki/PyYAMLDocumentation
使用其中之一:
$ your_other_program | python main.py
将其他程序的输出发送到 python,或使用 base64.b64encode(json.dumps(blah))
,您将获得像
'eyJtQXV0b21hdGljVGVzdExpc3QiOiBbeyJtWSI6IDguMTE0MTA1LCAibU5hbWUiOiAiYWNjZWxlcmF0b3JFbnRpdHkiLCAibVRlc3RTdGF0dXMiOiB0cnVlLCAibVgiOiAzLjgwNDM1MTgsICJtWiI6IC0zLjM4OTU3MjF9LCB7Im1OYW1lIjogImJhcm9tZXRlckVudGl0eSIsICJtVmFsdWUiOiAwLCAibVRlc3RTdGF0dXMiOiBmYWxzZX1dLCAibUF1dG9tYXRpY1Rlc3RDb21wbGV0ZWQiOiB0cnVlfQ=='
放入命令行,然后将其从 base64
解码回 JSON。
或者,更好的是,使用:
$ your_other_program >output_file.tmp
$ python main.py < output_file.tmp
$ rm output_file.tmp
好的,这是我的测试脚本:
print("original sys.argv output\n" + (sys.argv[1]))
string_temp=(yaml.load(sys.argv[1]))
print ("first transformation\n" +string_temp)
string_temp=string_temp.replace(":",": ")
dict_in=yaml.load(string_temp)
print("This is the dictionary")
print(dict_in)
这是我在控制台中输入的内容
python test_script.py """{foo:bar, id:23}"""
这是输出
original sys.argv output
"{foo:bar, id:23}"
first transformation
{foo:bar, id:23}
This is the dictionary
{'foo': 'bar', 'id': 23}
这仅在我使用三重引号 (""") 时有效。如果我使用 (") 或 (') 定义输入字符串,我会收到错误消息。
或者可以从 sys.argv[1]
print("original sys.argv output\n" + (sys.argv[1]))
string_temp=(sys.argv[1])[1:-1]
print ("first transformation\n" +string_temp)
string_temp=string_temp.replace(":",": ")
dict_in=yaml.load(string_temp)
print("This is the dictionary")
print(dict_in)