脚本解析 Cocos 的UI编辑器 Cocostudio 的csd导出的json文件

  • 一个小脚本,主要是为了免得趴显示器上一个一个找子节点,挺费眼的。
  • 主要功能是解析json内容,使用了python的json解析,解析出每一个子节点的名字,把所有父节点的名字和自己的名字拼起来用.分割
  • 生成结果形如 _json_name.parent1_p2_p3_newnode = “parent1.p2.p3.newnode”;
  • 可以使用代码(需要增加解析函数)直接调用getChild(rootNode,_json_name.parent1_p2_p3_newnode) 来获得子节点,省的保存多个节点或者一直getChildByName的写法.
#!/usr/bin/python
#
# Parse the csd file, parse the name of the child node and generate the name of the connection.
# Result: javascript code.
# Author: WangKun
# Email: [email protected]

import sys,json

file_object = open(sys.argv[1])
file_object = file_object.read( )
str = json.loads(file_object)
str = str['Content']['Content']['ObjectData']['Children']

path = ''
print_str = '''
    var _json_names = {} 
'''

def printPath( path ):
    global print_str
    print_str +=  "    _json_names." + path.replace('.','_') + " = " + '"' + path + '";\n'

def getName( parent ):
    for child in parent:
        global path
        old = path
        path = path + child['Name']
        printPath(path)
        if( 'Children' in child ):
            path += "."
            getName( child['Children'] )
        path = old
def main():
    global str,print_str
    getName( str )
    print print_str
if __name__ == '__main__':
    main()

脚本没有判断参数正确性,直接用第一个参数作为json文件名执行。
使用:

./parse.py PlayerInfo.json
    var _json_names = {}
    _json_names.a1_1 = "a1_1";
    _json_names.back = "back";
    _json_names.rbg = "rbg";
    _json_names.rb = "rb";
    _json_names.rb_level = "rb.level";
    _json_names.rb_level_lbl = "rb.level.lbl";
    _json_names.rb_score = "rb.score";
    _json_names.rb_score_lbl = "rb.score.lbl";
    _json_names.rb_Image_14 = "rb.Image_14";
    _json_names.rb_right = "rb.right";

解析函数:

// getChildbyName split with .
var getChild = function( nodeName,parent )
{
    if( !nodeName || !parent ) return false;
    if( nodeName.indexOf(".") == -1 ) return parent.getChildByName(nodeName);
    var node  = undefined;
    var names = nodeName.split(".");
    for ( var idx = 0;idx < names.length;idx ++ )
    {
        parent = parent.getChildByName( names[idx] );
        if( !parent ) break;
        if( idx == names.length - 1) {node = parent;}
    }
    return node;
}

// 调用
getChild( _json_names.rb_Image_14, ccsnode )

你可能感兴趣的:(技术,Cocos,Cocostudio,脚本工具)