码迷,mamicode.com
首页 > Web开发 > 详细

json,dict数据写入自动排版

时间:2016-07-21 18:09:55      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:

import json

with open(config.json) as f:
    result = json.loads(f.read())

with open(testconfig.json, wb) as f:
    space_count = 0
    last_char = ‘‘
    current = ‘‘
    is_in_double_quote = False
    for current_char in json.dumps(result):
        last_char = current
        current = current_char
        if is_in_double_quote:
            if current_char == ":
                if last_char == "\\":
                    f.write(current_char)
                else:
                    is_in_double_quote = not is_in_double_quote
                    f.write(current_char)
            else:
                f.write(current_char)
        else:
            if current_char == ":
                is_in_double_quote = not is_in_double_quote
                f.write(current_char)
            elif current_char == {:
                space_count += 1
                j = 0
                current_char += \n
                while j < space_count:
                    current_char +=     
                    j += 1
                f.write(current_char)
            elif current_char == }:
                space_count -= 1
                j = 0
                add_space = \n
                while j < space_count:
                    add_space +=     
                    j += 1
                current_char = add_space + current_char
                f.write(current_char)
            elif current_char == ,:
                current_char += \n
                j = 0
                while j < space_count - 1:
                    current_char +=     
                    j += 1
                f.write(current_char +    )
            else:
                f.write(current_char)

思路:

读取当前字符

1. 首先判断是否在 ‘ " ‘ 中

  1.1. 在 ‘ " ‘ 中则判断当前这个字符是否是 ‘ " ‘

    1.1.1. 如果不是则直接写入

    1.1.2. 如果是 ‘ " ‘,则需要判断是否有转义字符 ‘ \ ‘

      1.1.2.1. 如果有则直接写入

      1.1.2.2. 如果没有则退出 ‘ " ‘ 状态

  1.2. 不在 ‘ " ‘ 中,判断当前字符类型

    1.2.1. 当前字符是 ‘ " ‘ ,则进入 ‘ " ‘ 状态

    1.2.2. 当前字符是 ‘ { ‘  ‘ } ‘  ‘ , ‘ 这三个则会进行相应的换行添加空格操作

json,dict数据写入自动排版

标签:

原文地址:http://www.cnblogs.com/MrYuandeblog/p/5692424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!