python - 如何获得array("name" => "peter", "image_list" => array( 0 => array("src" => "http://www.abc.com/1.jpg", "href" => "
高洛峰
高洛峰 2017-04-17 13:08:08
0
2
495

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

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

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
刘奇

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
阿神
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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template