Perl JSON如何在解码给定的json文件时处理密钥覆盖

时间:2016-11-24 15:06:50

标签: json perl

我想解码一个具有以下结构的给json文件。当我将其解码为perl时,我的问题如下:我与切片有关键冲突。有没有办法从json解码中获取一个不会覆盖冗余元素的哈希结构?我可以想到阵列,欢迎任何想法和建议。

 "register": {

     "name"       : "CTRL",
     "desc"       : "Control Register 1",
     "mode"       : "rw",
     "reset_value": "0x0000_0000", 
     "addr_offset": "+0x4",

     "slice": {
       "name": "Reserved",
       "msb" : 3,
       "lsb" : 2,
       "desc": "Reserved. Leave 0."
     },

     "slice": {
       "name": "en",
       "msb" : 1,
       "lsb" : 1,
       "desc": "Port enable"
     },

     "slice": {
       "name": "Lbm",
       "msb" : 0,
       "lsb" : 0,
       "desc": "Loop back mode"
     }

  },

1 个答案:

答案 0 :(得分:5)

根据JSON spec

  

对象中的名称应该是唯一的。

所以'正确'的答案是 - 不要使用重复键做JSON,使用数组。

{
  "register": {
    "name":        "CTRL",
    "desc":        "Control Register 1",
    "mode":        "rw",
    "reset_value": "0x0000_0000",
    "addr_offset": "+0x4",
    "slices": [
      {
        "name": "Reserved",
        "msb":  3,
        "lsb":  2,
        "desc": "Reserved. Leave 0."
      },
      {
        "name": "en",
        "msb":  1,
        "lsb":  1,
        "desc": "Port enable"
      },
      {
        "name": "Lbm",
        "msb":  0,
        "lsb":  0,
        "desc": "Loop back mode"
      }
    ]
  }
}

然后在perl中解码:

my $stuff = decode_json(
   do { local $/; <$input> }
);

print Dumper $stuff;

迭代:

foreach my $slice ( @{$stuff -> {register} -> {slices}} ) {
   print Dumper $slice;
}

但是如果你真的必须,你可以使用JSONincremental parsing