【问题标题】:JSON string in MySQL to json responseMySQL中的JSON字符串到json响应
【发布时间】:2017-04-11 13:00:38
【问题描述】:

我有一个 JSON 格式的字符串存储在 mysql 数据库的列 (meta_data) 中,存储在表中它看起来像这样,例如:

 {"Format":"JPEG","Geometry":"3216x2136","size":{"width":3216,"height":2136}}

现在,如果我使用以下内容:

 $meta_data = DB::query->get();
 return $meta_data;

我明白了:

 [
   {
     "meta_data": "{\"Format\":\"JPEG\",\"Geometry\":\"3216x2136\",\"size\":{\"width\":3216,\"height\":2136}
   }
 ]

如果我使用,我也会得到相同的结果:

 $meta_data = json_decode(DB::query->get());
 return $meta_data;

同样,使用 response()->json($meta_data);将其作为字符串返回。

在我看来,它需要更进一步,但我无法得到任何接近我所追求的东西,理想情况下:

 [
   {
     "meta_data":
     { 
      "Format":"JPEG",
      "Geometry":"3216x2136",
      "size":
      {
        "width":3216,
        "height":2136
     }
   }
  }
 ]

【问题讨论】:

  • 你想把 josn 改成数组吗?或者请清楚你的问题是什么?

标签: php json response lumen


【解决方案1】:

DB::query->get() 将返回一个 stdClass 对象数组(假设 query 只是您查询条件的简写)。您将需要遍历数组并将每个条目的 meta_data 字段手动转换为 json 对象。

$records = DB::query->get();

foreach ($records as $record) {
    $record->meta_data = json_decode($record->meta_data);
}

return $records;

另一种选择是为表创建一个模型,然后将meta_data 字段添加到$casts 属性以自动将其转换为json。

型号:

class Attachment extends Model
{
    protected $casts = [
        'meta_data' => 'json',
    ];
}

控制器:

// assume "query" is shorthand for your query conditions
$records = Attachment::query->get();

return $records;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    相关资源
    最近更新 更多