drol55885602 2015-07-24 18:26
浏览 96

访问Json对象PHP(字符串不是数组)

Yes, I have read previous questions and I know how to access a JSON object and how to convert it into an array. I know about json_encode/decode. My problem is that my JSON response has a string, arrays and all and it will always return NULL when I access the data directly.

  object(Unirest\Response)#8 (4) {
    ["code"]=>
      int(200)
    ["body"]=>
      string(666) "{ "ticker": "AAPL:US", ".."
    ["headers"]=>
    array(9) {
    [0]=>
    string(15) "HTTP/1.1 200 OK"

Normally you would be able to directly access the object like this and this worked just fine when I last accessed the script a few days ago:

$response->body->ticker

Or you could use json_decode with true to turn it into an array.

$array = json_decode($response->body, true);

However, all of this no longer works. I believe they changed something with the output because it was working just a while ago but I have no clue. Any idea how to access the ticker data? I tested it with a different API and the same commands are working just fine to retrieve data from a different API, but the output seems to be different.

  • 写回答

2条回答 默认 最新

  • doujingxi3356 2015-07-24 18:36
    关注

    $response->body is a json string assuming you didnt shorten it so much as to loose someting important and therefore needs to be seperately converted to a PHP data item.

    As its a json string representing an object why not convert it to a PHP object like so

    $body = json_decode($response->body);
    

    Then you can address its properties like

    $body->ticker
    

    Alternatively

    $response->body = json_decode($response->body);
    

    Now you can address it as you expected i.e.

    $response->body->ticker
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么