使用 Laravel Blade 从 Postgres 显示 JSON 数据

Posted

技术标签:

【中文标题】使用 Laravel Blade 从 Postgres 显示 JSON 数据【英文标题】:Displaying JSON Data From Postgres WIth Laravel Blade 【发布时间】:2018-06-04 16:19:09 【问题描述】:

我有一个 postgres 数据库,它有一个包含两列的表('id' 是主键,'data' 是存储具有标题、内容等的 JSONB 数据集)。

目前,我只能显示整个表格或每个“数据”,但我无法从“数据”中提取单个数据,即标题。

这是路线,我尝试将数据作为 json 提取,以及 json 解码:

Route::get('/home', function () 
    $articles = DB::table('articles')->get();
    $results = json_decode($articles, true);
    return view('home', compact('articles', 'results'));
);

home.blade.php 模板。我试过使用文章和结果来显示标题。我能得到的最好的结果是显示整个表格,但我无法调用标题:

@foreach ($results as $result)            
  <div> $result->title </div>
@endforeach 

@foreach ($articles as $article)            
  <div> $article->title </div>
@endforeach 

@foreach ($results as $result)            
  <div>$result['data']</div> //this shows the whole json object, posted below
@endforeach

 @foreach ($results as $result)            
  <div>$result['data']['title']</div> //I believe this should work, but I get Illegal String Offset 'title' as an error,
 @endforeach 

我遇到的一些错误:

htmlspecialchars() expects parameter 1 to be string, array given
Array to string conversion
Illegal string offset 'title'
Something about calling something that's not there

这是 json_decode 之后 json 对象的样子(来自上面的 $result['data']):

"url": "http://omgili.com/ri/.wHSUbtEfZQrTHDoKYSJbjrpQN.N5MJgWJskXd50cUpWKooC_zdZBj5IfjtQ82V5YE9KjMI9MkoEoWsmLqcSDiWUKMSrDShx9H3vPUjRQuW0sylmueXyZg--", "text": "Cable companies are ove....", "uuid": "8c43aa206860570df0a86ff11f619235dea6e2bf", "title": "Cable companies are looking for ways to limit password sharing", "author": "theverge.com", "rating": null, "thread": "url": "http://omgili.com/ri/.wHSUbtEfZQrTHDoKYSJbjrpQN.N5MJgWJskXd50cUpWKooC_zdZBj5IfjtQ82V5YE9KjMI9MkoEoWsmLqcSDiWUKMSrDShx9H3vPUjRQuW0sylmueXyZg--", "site": "theverge.com", "uuid": "8c43aa206860570df0a86ff11f619235dea6e2bf", "title": "Cable companies are looking for ways to limit password sharing", "social": "vk": "shares": 0, "gplus": "shares": 0, "facebook": "likes": 0, "shares": 0, "comments": 0, "linkedin": "shares": 0, "pinterest": "shares": 0, "stumbledupon": "shares": 0, "country": "US", "published": "2017-12-20T18:17:00.000+02:00", "site_full": "www.theverge.com", "site_type": "news", "main_image": "https://cdn.vox-cdn.com/thumbor/wCruRyorIkyClceG2T4Q0BsYk7Y=/0x73:1020x607/fit-in/1200x630/cdn.vox-cdn.com/assets/4562901/theverge1_1020.jpg", "spam_score": 0, "title_full": "Cable companies are looking for ways to limit password sharing - The Verge", "domain_rank": 496, "site_section": "http://www.theverge.com/tech/rss/index.xml", "replies_count": 0, "section_title": "The Verge - Tech Posts", "site_categories": ["media"], "performance_score": 0, "participants_count": 1, "crawled": "2017-12-20T18:29:59.008+02:00", "entities": "persons": ["name": "rutledge", "sentiment": "none", "name": "tom rutledge", "sentiment": "none"], "locations": [], "organizations": ["name": "netflix", "sentiment": "none", "name": "bloomberg", "sentiment": "none", "name": "viacom", "sentiment": "none", "name": "ubs", "sentiment": "none", "name": "espn", "sentiment": "none"], "language": "english", "published": "2017-12-20T18:17:00.000+02:00", "highlightText": "", "ord_in_thread": 0, "external_links": [], "highlightTitle": ""

【问题讨论】:

【参考方案1】:

您的代码的问题是当您从 Postgres 查询数据时,Eloquent 会返回一个 Collection 对象而不是 JSON 字符串。因此,行:

$results = json_decode($articles, true);

从不工作。由于json_decode 函数仅适用于字符串(特别是UTF8 编码的字符串)。

您看到的错误是因为$article-&gt;data 实际上没有被解析并且仍然是一个字符串。

将字符串视为数组时会发生Array to string conversionIllegal string offset 错误。

基本上要正确解析/解码 JSON 数据,您必须遍历集合并手动转换它。您可以使用Eloquent\Collection::map 函数将数据正确映射到关联数组:

$results = $articles->map(function($article)
   return [
      'id' => $article->id,
      'data' => json_decode($article->data, true)  
   ];
)

【讨论】:

感谢您的详尽解释和回答!

以上是关于使用 Laravel Blade 从 Postgres 显示 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

从 Laravel Blade 中的 JSON 中选择值

从(Laravel 8)Blade 模板文件调用函数

Laravel 中的 Blade 模板与普通 php

Laravel“属于”功能。不完全确定这是如何工作的。帮助从 Blade 模板访问相关模型信息

Laravel - 大量使用 Blade 渲染视图的访问器(修改器)

从 laravel/blade 中的数组创建逗号分隔列表?