Python生成Json的Schema及相关函数 郝伟,2020/01/22 [TOC]

1. 简介

对于比较大的Json文件,其结构往往难以理解,所以本文提供了相应的代码能够对此Json文件生成以下快速生成如下所示的内容:

另外,本文还提供了Json和XML互转的功能函数。

.$schema
.definitions
.definitions.edge
.definitions.edge.type
.definitions.edge.properties
.definitions.edge.properties.edgeName
.definitions.edge.properties.edgeName.type
.definitions.edge.properties.edgeName.id
.definitions.edge.properties._id
.definitions.edge.properties._id.type
.definitions.edge.properties._id.id
.definitions.edge.properties._inV
.definitions.edge.properties._inV.type
.definitions.edge.properties._inV.id
.definitions.edge.properties._outV
.definitions.edge.properties._outV.type
.definitions.edge.properties._outV.id
.definitions.edge.properties._label
.definitions.edge.properties._label.type
.definitions.edge.properties._label.id
.definitions.edge.properties._type
.definitions.edge.properties._type.type
.definitions.edge.properties._type.id
.definitions.edge.properties.description

[...]

.properties.vertices.items
.properties.vertices.items.anyOf
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]
.properties.vertices.items.anyOf    [...]

2. 源代码

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import json
import xmltodict

# json转xml函数
def json_to_xml(json_str):
    # xmltodict库的unparse()json转xml
    # 参数pretty 是格式化xml
    xml_str = xmltodict.unparse(json_str, pretty=1)
    return xml_str

# 定义xml转json的函数
def xml_to_json(xml_str):
    # parse是的xml解析器
    xml_parse = xmltodict.parse(xml_str)
    # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
    # dumps()方法的ident=1,格式化json
    json_str = json.dumps(xml_parse, indent=1)
    return json_str

def load_json(jsonfile):
    data = []
    with open(jsonfile, 'r') as load_f:
         data =  json.load(load_f)
    return data

def str_to_file(filename, str1, code='utf-8'):
    with open(filename, 'w', encoding=code) as f:
        f.write(str1)

def json_to_xml_test():
    xmlstr = """<?xml version="1.0" encoding="utf-8"?>
        <user_info>
            <id>12</id>
            <name>Tom</name>
            <age>12</age>
            <height>160</height>
            <score>100</score>
            <variance>12</variance>
        </user_info>
    """

jsonstr = {
    "user_info": {
        "id": 12,
        "name": "Tom",
        "age": 12,
        "height": 160,
        "score": 100,
        "variance": 12
    }
}

fin1 = "input.json"
fin2 = "scheme.json" 
fin3 = 'test.json'
fout = R'sample.xml'

# str_to_file(fout, json_to_xml(data))
data = load_json(fin2)



paths = []
def show(data, prefix=''):
    if isinstance(data, dict):
        for key in data:
            #if key == 'allOf':
            #    continue
            path = prefix + '.' + key
            if paths.count(path) == 0:
                paths.append(path)
                show(data[key], prefix +'.' + key)
    elif(isinstance(data, list)):
        for item in range(len(data)):
            if item == "allOf":
                paths.append(prefix +'\t[...]')
            elif(paths.count(prefix) == 0):
                show(item, prefix +'\t->')
            else:
                paths.append(prefix + "\t[...]")

def show1(data, prefix=''):
    if len(prefix) == 0:
        paths.append('root')

    if isinstance(data, dict):
        for key in data:
            path = prefix + '\t' + key
            #print(path)
            #if paths.count(path) > 0:
            #    continue
            paths.append(path)
            show(data[key], prefix +'\t')
    elif(isinstance(data, list)):
        for item in data:
            show(item, prefix +'\to')
    else:
        pass

show(data)

print(' Available Paths '.center(80, '-'))

for path in paths:
    print(path)

str_to_file('out1.txt', '\n'.join(paths))

#print("--------------------------- json to xml ----------------------------------")
#print(json_to_xml(jsonstr))
#print("--------------------------- xml to json ----------------------------------")
#print(xml_to_json(xmlstr))
#print("-------------------------------------------------------------------")

results matching ""

    No results matching ""