开发者

Convert JSON in print format to valid JSON

开发者 https://www.devze.com 2023-01-17 09:54 出处:网络
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.

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 yo开发者_StackOverflowu!

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


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

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


References:
- file_get_contents()
- json_decode()

0

精彩评论

暂无评论...
验证码 换一张
取 消