python 将json数据提取转化为txt的方法

yipeiwu_com6年前Python基础

如下所示:

#-*- coding: UTF-8 -*-
import json
import pymysql
import os
import sys
# 数据类型
# {
#  "name": "score.networkQuality",
#  "index": true,
#  "view": "app/views/score/networkQuality.tmpl.html",
#  "files": ["app/modules/controllers/score/networkQualityCtrl.js"]
# },
name = []
index = []
views = []
files = []
# "name": "monitored.monitored",
with open('C:\\Users\\sxf\\Desktop\\app-modules.json') as f:
 for line in f:
  try:
   line.index("name")
   # line = line.strip('\n')
   pos = line.index(':')
   name.append(line[pos+3:len(line)-3])
  except ValueError:
   pass
  try:
   line.index("true")
   # line = line.strip('\n')
   pos = line.index(':')
   index.append((line[pos+2:len(line)-2]))
  except ValueError:
   pass
  try:
   line.index("view")
   try:
    line.index("name")
   except ValueError:
    pos = line.index(':')
    views.append(line[pos + 3:len(line) - 3])
  except ValueError:
   pass
  # ['app/modules/controllers/monitored/monitoredCtrl.js","app/modules/services/resources/resourcesService.j']
  try:
   line.index("files")
   # line = line.strip('\n')
   pos = line.index(":")
   try:
    i=0
    str1 = ""
    str2 = ""
    str3 = ""
    pos_comma = line.index(",")
    str = line.split(',')
    comma_count = line.count(',')
    while i<=comma_count:
     if i == 0:
      # str[0] = str[0].strip('\n')
      str1 = str[0][pos+4:len(str[0])-1]
     elif i == 1 :
      if comma_count == 1:
       # str[1] = str[1].strip('\n')
       str2 = str1+','+str[1][1:len(str[1])-3]
      else:
       str2 = str1 + ',' + str[1][1:len(str[1]) - 1]
     elif i == 2 :
      # str[2] = str[2].strip('\n')
      str3 = str2+','+str[2][1:len(str[2])-3]
     else:
      pass
     i = i + 1
    if (comma_count == 1):
     files.append(str2)
    elif (comma_count == 2):
     files.append(str3)
   except ValueError:
    # line = line.strip('\n')
    files.append(line[pos+4:len(line)-3])
    pass
  except ValueError:
   pass
 if os.path.exists("C:\\Users\\sxf\\Desktop\data.txt"):
  os.remove("C:\\Users\\sxf\\Desktop\data.txt")
 write_file = open("C:\\Users\\sxf\\Desktop\data.txt","a+")
 j=0
 while j< len(name):
  str_info = name[j]+"\t"+index[j]+"\t"+views[j]+"\t"+files[j]+"\n"
  write_file.write(str_info)
  j = j + 1

以上这篇python 将json数据提取转化为txt的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python将多个文本文件合并为一个文本的代码(便于搜索)

但是,当一本书学过之后,对一般的技术和函数都有了印象,突然想要查找某个函数的实例代码时,却感到很困难,因为一本书的源代码目录很长,往往有几十甚至上百个源代码文件,想要找到自己想要的函数实...

Python中使用第三方库xlutils来追加写入Excel文件示例

目前还没有更好的方法来追写Excel,lorinnn在网上搜索到以及之后用到的方法就是使用第三方库xlutils来实现了这个功能,主体思想就是先复制一份Sheet然后再次基础上追加并保存...

Python和Go语言的区别总结

什么是Python? Python是一种功能强大的高级编程语言,主要用于科学和工程计算。它是一种高效的语言,优雅务实,简单而强大,适合新手和专业人士的编程。 Python支持多种编程范例...

python中的一些类型转换函数小结

函数               &...

python 解析XML python模块xml.dom解析xml实例代码

一 、python模块 xml.dom 解析XML的APIminidom.parse(filename)加载读取XML文件 doc.documentElement获取XML文档对象 no...