简体   繁体   English

将打印格式的JSON转换为有效JSON

[英]Convert JSON in print format 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. 我有一个文本文件,其格式类似于JSON,但具有打印/查看友好的格式,我想将该字符串转换为有效的JSON。 Basically, I want to read the file using PHP5 and call json_decode to deserialize the string. 基本上,我想使用PHP5读取文件并调用json_decode以反序列化字符串。 But, json_decode is not able to parse the "print-friendly" json string. 但是,json_decode无法解析“打印友好”的json字符串。

I am getting error 4 Invalid or malformed JSON. 我收到错误4无效或格式错误的JSON。

It looks like someone else had a similar issue as me: PHP json_decode() returns NULL with valid JSON? 看来其他人也有与我类似的问题: PHP json_decode()返回带有有效JSON的NULL?

I am using notepad++ to write the json file. 我正在使用notepad ++编写json文件。

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; 我对得到的json字符串进行了var_dump处理,并将http://jsonlint.com/标记为有效json; however, json_decode is not able to deserialize the json string for some reason. 但是,由于某种原因,json_decode无法反序列化json字符串。

Thank you! 谢谢!

SOLUTION I set the encoding of the text file to UTF-8 without BOM and it works fine now. 解决方案:我将文本文件的编码设置为不带BOM的UTF-8,现在可以正常工作。 thank you all! 谢谢你们!

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

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


References: 参考文献:
- file_get_contents() file_get_contents()
- json_decode() json_decode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM