aaronpk / XRay

X-Ray returns structured data from any URL
https://xray.p3k.app
MIT License
90 stars 15 forks source link

Converting XRay to JF2 #115

Closed barnabywalters closed 1 year ago

barnabywalters commented 1 year ago

The output of XRay is almost compatible with JF2 as-is. aaronpk stated that JF2 compatibility is not a goal of XRay, which is absolutely understandable.

I’m leaving this issue here both to document this approach (preempting similar issues from being raised in the future when the question has already been answered) and to drop this code snippet for anyone who wants to convert XRay data into something which is more compatible with JF2 — namely renaming refs to references and items to children, which were the most notable differences I ran into.

function xRayToJf2(array $x) {
    $convertRecursive = function ($value) use (&$convertRecursive) {
        if (is_array($value)) {
            $converted = [];
            foreach ($value as $k => $v) {
                if ($k == 'items') {
                    $k = 'children';
                } elseif ($k == 'refs') {
                    $k = 'references';
                }
                $converted[$k] = $convertRecursive($v);
            }
        } else {
            $converted = $value;
        }

        return $converted;
    };

    return $convertRecursive($x);
}