虽然我在Stackoverflow周围搜索过,但我找不到符合我问题的答案。 UseCase:我想访问服务器端json以将其与Google Chart API或Highcharts一起使用。他们俩都需要一个合适的json文件。 找到我的方法:
Json-File (sampledata.json)
[{
"timestamp": "2014-05-22T12:15:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T12:30:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T12:45:00+02:00",
"value": 236.0
}, {
"timestamp": "2014-05-22T13:00:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T13:15:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T13:30:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T13:45:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T14:00:00+02:00",
"value": 235.0
}, {
"timestamp": "2014-05-22T14:15:00+02:00",
"value": 234.0
}, {
"timestamp": "2014-05-22T14:30:00+02:00",
"value": 233.0
}, {
"timestamp": "2014-05-22T14:45:00+02:00",
"value": 233.0
}, {
"timestamp": "2014-05-22T15:00:00+02:00",
"value": 233.0
}, {
"timestamp": "2014-05-22T15:15:00+02:00",
"value": 233.0
}]
php-File读取json文件:
<?php
// It reads a json formatted text file and outputs it.
$json = file_get_contents("sampledata.json");
var_dump($json);
?>
生成的输出类似于以下内容:
string(832) "[{ "timestamp": "2014-05-22T12:15:00+02:00", "value": 235.0 }, { "timestamp": "2014-05-22T12:30:00+02:00", "value": 235.0 }, { "timestamp": "2014-05-22T12:45:00+02:00", "value": 236.0 }, { "timestamp": "2014-05-22T13:00:00+02:00", "value": 234.0 }, { "timestamp": "2014-05-22T13:15:00+02:00", "value": 234.0 }, { "timestamp": "2014-05-22T13:30:00+02:00", "value": 234.0 }, { "timestamp": "2014-05-22T13:45:00+02:00", "value": 234.0 }, { "timestamp": "2014-05-22T14:00:00+02:00", "value": 235.0 }, { "timestamp": "2014-05-22T14:15:00+02:00", "value": 234.0 }, { "timestamp": "2014-05-22T14:30:00+02:00", "value": 233.0 }, { "timestamp": "2014-05-22T14:45:00+02:00", "value": 233.0 }, { "timestamp": "2014-05-22T15:00:00+02:00", "value": 233.0 }, { "timestamp": "2014-05-22T15:15:00+02:00", "value": 233.0 }]"
如您所见,这不是一个合适的json输出。第一个字符string(832) "
和最后一个"
必须被删除 - 然后它才会起作用。我已经尝试过使用php函数json_decode
,但这并没有解决我的问题。实际上它也生成一个数组而没有json对象。
所以我的问题是:
提前致谢!
答案 0 :(得分:2)
如果要按原样使用json对象,则无需通过json_decode
或json_encode
运行它。只需file_get_contents
即可获得该文件的内容(这是一个准确的函数名称)。然后将其传递给Google API或您要使用的任何其他内容。您的问题来自var_dump
,您似乎认为string(832)
是变量$json
内容的一部分,而它实际上只是var_dump
'的一部分输出。
答案 1 :(得分:0)
使用json_encode json_decode
$json_o = json_decode(file_get_contents("sampledata.json")); // object
$json_a = json_decode(file_get_contents("sampledata.json", true)); // associative array