代码之家  ›  专栏  ›  技术社区  ›  valenzio

使用不带转义的shell将JSON字符串转换为字典

  •  -1
  • valenzio  · 技术社区  · 6 年前

    我用一个输入参数从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。我不能使用转义字符,因为字符串是由其他程序提供的。

    有优雅的方法来解决这个问题吗?

    4 回复  |  直到 6 年前
        1
  •  1
  •   imans77    6 年前

    >>> str = '{foo: bar, id: 23}'
    

    yaml

    >>> import yaml
    >>> dict = yaml.load(str)
    >>> dict
    {'foo': 'bar', 'id': 23}
    
    >>> dict['foo']
    'bar'
    

    https://pyyaml.org/wiki/PyYAMLDocumentation

        2
  •  1
  •   Dusan Gligoric    6 年前

    "{\"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'}
    

    """{"key1":"value1", "key2":"value2"}""" "" + "{" + key1 + ":" + value1 + ", " + + key2 + ":" + value2 + "}" + "" bash python

    """{"'"key1"'":"'"value1"'", "'"key2"'":"'"value2"'"}"""

        3
  •  0
  •   lenik    6 年前

    $ your_other_program | python main.py
    

    base64.b64encode(json.dumps(blah))

    base64

    $ your_other_program >output_file.tmp
    $ python main.py < output_file.tmp
    $ rm output_file.tmp
    
        4
  •  0
  •   valenzio    6 年前

    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)