首頁  >  問答  >  主體

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":"#"
        }
    ]
}

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

高洛峰高洛峰2722 天前463

全部回覆(2)我來回復

  • 怪我咯

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

    笨辦法:

    取得name值

    1. 取到array("name" => "位置,為截取開始
    2. 取到起始位置的最近的引號位置,為截取結束,如果名稱中有轉義引號,需要判斷引號前一位置是否為斜槓
    3. 截取到name值

    取得image_list值

    1. 先用上面的方法取得array(0 => ....) 字串
    2. 然後用正規split將array分成數組
    3. 然後用上面的方法取到各個值

    回覆
    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))
    

    這玩意兒的格式其實就是php輸出的,最好還是用php估計你也知道的,我這個實現也就是給你看一下,都差不多的原理,就是回調

    回覆
    0
  • 取消回覆