如何使用PHP解码包含对其他json文件的引用的json数据库文件?目标是获得一个加载了所有引用的对象。
带有引用的json数据库文件示例:
{
"id": 12,
"title": "Credit card number disclosure",
"severity": "medium",
"description": {
"$ref": "#/files/description/12"
},
"fix": {
"effort": 50,
"guidance": {
"$ref": "#/files/fix/57"
}
},
"cwe": [
"200"
],
"references": [
{
"url": "http://en.wikipedia.org/wiki/Luhn_algorithm",
"title": "Wikipedia - Luhn algorithm"
},
{
"url": "http://en.wikipedia.org/wiki/Bank_card_number",
"title": "Wikipedia - Bank card number"
}
]
}
带有file_get_contents()
的 json_decode()
不会自动加载引用。
答案 0 :(得分:0)
<?PHP
$json_file = file_get_contents("db.json");
$json = json_decode($json_file);
function walkObject($obj) {
foreach($obj as $prop => $value) {
if (is_object($value))
$obj->$prop = walkObject($value);
if ($prop == "\$ref")
$obj->$prop = walkObject(json_decode(file_get_contents($value)));
}
return $obj;
}
这将加载您的初始json文件,对其进行解码并递归遍历。每次看到$ ref属性-它将尝试读取指向的文件以对其进行解码,然后递归遍历...
您应该检查一下file_get_contents和json_decode的错误。