views:

84

answers:

1

Hello,

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: http://stackoverflow.com/questions/2410342/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!

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

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


References:
- file_get_contents()
- json_decode()

Peter Ajtai
Thank you. It turns out the file-encoding of my text file was off. I changed the encoding of the source file to UTF-8 without BOM and it works great now! thank you all for the great support!
AbeP