【问题标题】:How to decode array JSON objects without index quotation如何在没有索引引用的情况下解码数组 JSON 对象
【发布时间】:2016-03-12 14:56:54
【问题描述】:

我有这样的数组 JSON 对象:

 $json = [
           {name: "XCB808tvXNpqXKqekA2HlkJ8H.jpg", size: 5112},
           {name: "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", size: 13135}
         ]

由于某种原因,我没有在 namesize 索引中添加双引号,我想在 Laravel 5.1 中解码 JSON 并使用 foreach() 进行迭代。但是当像这样使用 foreach 时:

$json = json_decode($json,true);
         foreach ($json as $val) {
            Image::create(['filename' => $val['name'], 'size' => $val['size']]);
         }

然后误会我:

json_decode() expects parameter 1 to be string, array given

【问题讨论】:

  • 您的 JSON 数据来自哪里?
  • javascript (angularjs)
  • 为什么会出现这种错误的格式?它来自您自己的代码?如果是,你能显示js代码吗?这是因为是的,它可以在 php 中解决你的问题,但是如果你有一个有效的 JSON 会好得多
  • "我有这样的数组 JSON 对象:- 这不是 JSON。它看起来像有效的 Javascript ......但你似乎试图在 PHP 中使用该变量。我不是有效的 PHP .

标签: php arrays json laravel decode


【解决方案1】:

json_decode() 用于将 json 字符串解码为数组/数据对象。

json_encode() 从数组或数据创建一个 json 字符串。

更新:

错误消息清楚地告诉You are passing an array to json_decode, but it expects a string. 看起来你必须遍历数组:所以这样做。

foreach($arr as $i => $json) {
    $arr[$i] = json_decode($json, true);
}

使用这个 JSON。希望它会起作用。

[
  {
    "name": "XCB808tvXNpqXKqekA2HlkJ8H.jpg",
    "size": "5112"
  },
  {
    "name": "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg",
    "size": "13135"
  }
]

点击链接:

  1. http://php.net/manual/en/function.json-decode.php
  2. Key value pairs using JSON
  3. http://www.w3schools.com/json/json_syntax.asp

【讨论】:

  • 我想解码$json。我从 ajax 请求(javascript)中获取 $json
  • 问题标题:“如何解码没有索引引用的数组JSON对象”
猜你喜欢
  • 2021-01-26
  • 2011-05-06
  • 2017-05-07
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
  • 2010-11-25
  • 1970-01-01
相关资源
最近更新 更多