Home > Software engineering >  PHP Function to Restore JSON File from String?
PHP Function to Restore JSON File from String?

Time:05-01

I have a PHP script that pulls data from another program; that program outputs its data as a single JSON file. But for reasons I'll never understand, the author of the other program decided to remove all newlines and white spaces from the JSON file and submit the whole output as one enormous string:

{"John":{"status":"Wait"},"Jennifer":{"status":"Active"},"James":{"status":"Active","age":56}}

This is practically useless. I need my PHP script to take the above and reconstruct the original file into a human-readable format:

{
    "John": {
        "status":"Wait"
    },
    "Jennifer": {
        "status":"Active"
    },
    "James": {
        "status":"Active",
        "age":56
    }
}

I could develop such a method from scratch, but that would be a pain. I've been reading up on json_decode(), which I believe could help me parse the original string, but not really reconstruct the original file. Does anyone know of a library or something that might help? Thanks

CodePudding user response:

You can do it in two steps:

  1. decode JSON string into PHP array
  2. encode again using option JSON_PRETTY_PRINT
echo json_encode(json_decode($json_text, true), JSON_PRETTY_PRINT);

Test json_encode and json_decode

  • Related