Home  >  Q&A  >  body text

python - 如何获得array("name" => "peter", "image_list" => array( 0 => array("src" => "http://www.abc.com/1.jpg", "href" => "

给定的有xml文件,在该xml文件中可以获得name image_list等数据,现在需要将这些数据按照问题中的格式写入日志中。现在是用python处理xml文件,我考虑用json格式化数据,但json格式化的数据形式是:

{
    "name":"peter",
    "image_list" :[
        {
            "src":"http://www.abc.com/1.jpg",
            "href":"#"
        }
    ]
}

请问应该如何操作才能获得标题中所给定的格式?

高洛峰高洛峰2721 days ago455

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:10:08

    Stupid way:

    Get name value

    1. Get array("name" => "position, which is the beginning of interception
    2. Get the nearest quotation mark position from the starting position, which is the end of interception. If there are escaped quotation marks in the name, you need to determine whether the position before the quotation mark is a slash
    3. Intercept the name value

    Get image_list value

    1. First use the above method to get the array(0 => ....) string
    2. Then use regular split to divide the array into arrays
    3. Then use the above method to get each value

    reply
    0
  • 阿神

    阿神2017-04-17 13:10:08

    object = {"name": "peter",
              "image_list": [{"src": "http://www.abc.com/1.jpg", "href": "#"}]}
    
    
    def format_dict(dic):
        content = []
        for k in dic:
            content.append('"' + k + '" => ' + call(dic[k]))
        return 'array(' + ",".join(content) + ')'
    
    
    def format_list(arr):
        content = []
        for i in range(len(arr)):
            content.append(str(i) + ' => ' + call(arr[i]))
        return 'array(' + ",".join(content) + ')'
    
    
    def call(obj):
        if type(obj) == dict:
            return format_dict(obj)
        elif type(obj) == list:
            return format_list(obj)
        elif type(obj) == str:
            return '"' + obj + '"'
        else:
            return str(obj)
    
    
    print(call(object))
    

    The format of this thing is actually output by PHP. It is best to use PHP. I guess you know it. I just want to show you the implementation. The principle is the same, which is callback

    reply
    0
  • Cancelreply