将csv转换为json,并查找json中的数据

一.读取csv,并且转为json

json和字典不同,字典是一个特定数据结构,而json是一种数据的传输格式。通常先构造标准的数据结构格式dict,然后通过json.dumps(dict)方法将dict一次性转化为json格式。因此,需要读取csv文件,接着转为dict的格式,然后生成json数据。

def cvs2json(file_path):
    import json
    input_data=[]
    fo=open(file_path,"r", encoding="utf-8")
    for line in fo:
        line=line.replace("\n","")  #将换行换成空
        line_arr=line.split(",")
        while not line_arr[-1].strip():
            del line_arr[-1]
        input_data.append(line_arr)  #以,为分隔符
    fo.close()  #关闭文件流
    
    data={}
    for row_index in range(len(input_data)):
        row_data = input_data[row_index]
        sub_data = data
        col_len = len(row_data)
        for col_index in range(col_len):
            current_data = row_data[col_index]
            # 判断目标数据是否为空,且是否是最后一个元素
            if current_data != '':
                sub_data[current_data] = [{}] if col_index < col_len-1 else []
                if len(sub_data[current_data]) >0:
                    sub_data = sub_data[current_data][0]
            else:
                # 确定上一个条目
                pre_row_index = row_index
                while not input_data[pre_row_index][col_index].strip():
                    pre_row_index -= 1
                sub_data = sub_data[input_data[pre_row_index][col_index]][0]
    json_data = json.dumps(data, ensure_ascii=False)
    return(json_data)
print(cvs2json("test.csv"))

二.查找json中的数据

先将json loads为字典,接着对其进行遍历,匹配每次遍历的iterator是否等于key,如果是,则标记退出;如果不是,则以遍历的值作为其键,向下层继续遍历。

def find(key):
    import json
    data = json.loads(cvs2json("test.csv"))
    result = []
    def _find_key(data, key, result):
        checked = False
        for current_key in data:
            if key not in result:
                result.append(current_key)
                # 判断是否为key
                if current_key == key:
                    checked = True
                    return checked
                # 当前层找不到key,下层继续遍历
                if (not checked) & (len(data[current_key])!=0):
                    for sub_key in data[current_key]:
                        checked = _find_key(sub_key, key, result)
                if not checked:
                    result.pop()
        return checked
    _find_key(data,key,result)
    if not result:
        return '不存在关键字:{}'.format(key)
    return ','.join(result)
path = find('str')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值