1
votes

I have a text file that is formatted like JSON, but in a print/view friendly format and I want to convert that string to valid JSON. Basically, I want to read the file using PHP5 and call json_decode to deserialize the string. But, json_decode is not able to parse the "print-friendly" json string.

I am getting error 4 Invalid or malformed JSON.

It looks like someone else had a similar issue as me: PHP json_decode() returns NULL with valid JSON?

I am using notepad++ to write the json file.

So, how can I convert

FROM:

{
    "data": [
        {
            "thumbImg": "thumbImg",
            "street": "street",
            "city": "Fort Worth",
            "state": "Texas",
            "zip": "76192-0001",
            "url": "url"
        }
    ]
}

TO:

{"data":[{"thumbImg": "thumbImg", "street": "street", "city": "Fort Worth", "state": "Texas", "zip": "76192-0001", "url": "url"}]

I even tried doing the following:

<?php
$filename = "links.json";
$file = fopen($filename, "r");
    
$lines = file($filename);
    
$data = "";
;
foreach ($lines as $line_num => $line) {
    $formatted = trim($line);
    $formatted = str_replace("\r", "", $formatted);
    $formatted = str_replace("\n", "", $formatted);
    $data .= $formatted;        
}

$json = json_decode($data, true);
?>

I did a var_dump of the resulting json string and http://jsonlint.com/ marked it as valid json; however, json_decode is not able to deserialize the json string for some reason.

Thank you!

SOLUTION I set the encoding of the text file to UTF-8 without BOM and it works fine now. thank you all!

1
The data parses with no problems for me.Quentin
It works when I read from a text file (without mucking about with reformatting the text). It sounds like you have started with "I'm having problems reading a file" but you ended up asking "How can I reformat this file?", which is several steps down the line from the actual problem and has resulted in a question that isn't helpful to anyone.Quentin
json_decode works perfectly for me: codepad.org/wcNFa2F5 You should try file_get_contents to read the file: php.net/manual/en/function.file-get-contents.phpFelix Kling
Have you tried file_get_contents() instead? Also when you read using file() there is no need to call fopen().BoltClock
Ah, the byte-order mark must have been the cause of the parsing error.BoltClock

1 Answers

5
votes
<?php
$filename = "links.json";
$file = file_get_contents($filename);    

$json = json_decode($file, true);
?>


References:
- file_get_contents()
- json_decode()