如何拆分我的json文件?

时间:2015-07-07 09:09:52

标签: json

我正在将我的dnd的角色表从excel移动到json。 我希望保持我的档案“小”。

例如:

我可以写这个json:

character.json

"{  
    "title":"Main",
    "header":{  
        "name":"",
        "player":"",
        "classes":[  
            {  
                "name":"",
                "level":0
            }
        ],
        "level":"",
        "speed":0
    },
    "abilities":{  
        "ability":{  
            "name":"",
            "permanent":{  
                "score":"",
                "modifier":""
            },
            "temporary":{  
                "score":"",
                "modifier":""
            }
        }
    },
    "damageReduction":0,
    "hitPoint":{  
        "total":0,
        "current":0
    },
    "initiative":0
}"

as:

character.json

"{  
    "title":"Main",
    "header": header.json, // or anything working I don't mind
    "abilities":{  
        "ability":{  
            "name":"",
            "permanent":{  
                "score":"",
                "modifier":""
            },
            "temporary":{  
                "score":"",
                "modifier":""
            }
        }
    },
    "damageReduction":0,
    "hitPoint":{  
        "total":0,
        "current":0
    },
    "initiative":0
}"

header.json

{  
    "name":"",
    "player":"",
    "classes":[  
        {  
            "name":"",
            "level":0
        }
     ],
    "level":"",
    "speed":0
}

我在Google上尝试“json link”和其他一些关键字,但我没有找到任何相关内容。 (我发现json-ld并且它非常好但是偏离主题:))

编辑:

如果您认为我应该将我的问题转移到其他地方(programmers?),请在常规方面进行讨论。

1 个答案:

答案 0 :(得分:0)

好的,我将首先质疑你想要完成的事情。为什么要尝试将单个逻辑对象拆分为单独的元素?

但是,由于JSON是嵌套数据结构,您当然可以根据需要将其拆分。例如。如果你想分开你的'标题':

#!/usr/bin/perl

use strict;
use warnings;
use JSON;
use Data::Dumper;

my $json_str = '{  
    "title":"Main",
    "header":{  
        "name":"",
        "player":"",
        "classes":[  
            {  
                "name":"",
                "level":0
            }
        ],
        "level":"",
        "speed":0
    },
    "abilities":{  
        "ability":{  
            "name":"",
            "permanent":{  
                "score":"",
                "modifier":""
            },
            "temporary":{  
                "score":"",
                "modifier":""
            }
        }
    },
    "damageReduction":0,
    "hitPoint":{  
        "total":0,
        "current":0
    },
    "initiative":0
}';

my $json = decode_json($json_str);

## split out the 'header' element:
my $header_str = to_json( $json->{header}, { pretty => 1 } );
print "HEADER:\n";
print $header_str;

## insert a filename into the 'main' element:
delete( $json->{header} );
$json->{header} = "somefile.json";

print "REST:\n";
my $rest_of_json = to_json( $json, { pretty => 1 } );
print $rest_of_json;