2017-02-11 63 views
0

我有一个嵌套的JSON文件,它由键和值组成,它们只是字符串。但是JSON文件的结构并不固定,所以有时它可以嵌套3层,有时只有2层。 我想知道我可以如何在严格模式下序列化?在严格模式下反序列化JSON

"live" : { 
"host" : "localhost", 
"somevalue" : "nothing", 
"anobject" : { 
    "one" : "two", 
    "three" : "four", 
    "five" : { 
    "six" : "seven" 
    } 
} 

}

如果我想知道JSON的结构,我只是会写我自己的类,但由于密钥是不固定的,并且还嵌套可以分成几个层次,我真的很想知道如何将这样一个对象切割成特定的类型。

任何帮助或暗示赞赏

回答

0

我觉得invariant旨意为你服务好这里。首先,这可能是让你知道,你可以严格哈克输入一个密钥树:

<?hh // strict 
class KeyedTree<+Tk as arraykey, +T> { 
    public function __construct(
    private Map<Tk, KeyedTree<Tk, T>> $descendants = Map{}, 
    private ?T $v = null 
) {} 
} 

(那一定是因为cyclic shape definitions are sadly not allowed类)

我还没有尝试过,但type_structure s和Fred Emmott's TypeAssert看起来也有兴趣。如果已知JSON blob的某些部分已修复,那么可以使用invariant s隔离嵌套的不确定部分并从中构建一棵树。在整个BLOB是未知的极限情况,那么你可以切除TypeAssert因为没有有趣的固定结构断言:

use FredEmmott\TypeAssert\TypeAssert; 
class JSONParser { 
    const type Blob = shape(
     'live' => shape(
      'host' => string, // fixed 
      'somevalue' => string, // fixed 
      'anobject' => KeyedTree<arraykey, mixed> // nested and uncertain 
     ) 
    ); 
    public static function parse_json(string $json_str): this::Blob { 
     $json = json_decode($json_str, true); 
     invariant(!array_key_exists('anobject', $json), 'JSON is not properly formatted.'); 
     $json['anobject'] = self::DFS($json['anobject']); 
      // replace the uncertain array with a `KeyedTree` 
     return TypeAssert::matchesTypeStructure(
      type_structure(self::class, 'Blob'), 
      $json 
     ); 
     return $json; 
    } 
    public static function DFS(array<arraykey, mixed> $tree): KeyedTree<arraykey, mixed> { 
     $descendants = Map{}; 
     foreach($tree as $k => $v) { 
      if(is_array($v)) 
       $descendants[$k] = self::DFS($v); 
      else 
       $descendants[$k] = new KeyedTree(Map{}, $v); // leaf node 
     } 
     return new KeyedTree($descendants); 
    } 
} 

沿着这条路走下去,你仍然必须补充的KeyedTreecontainsKey不变,但这是Hack中非结构化数据的现实。

+0

非常感谢您的意见! – Bearzi