javascript - 如何显示来自 JSON 字符串转换数组的数据
问题描述
我想通过将字符串转换为数组来显示 JSON 字符串中的一些数据
我使用 json_decode 将 json 字符串转换为数组。这是我的 json 字符串(dd):
"{"title":"W3Schools Online Web Tutorials","description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}"
当我返回数组或 dd 数组时,会按预期显示数组(dd):
array:4 [▼"title" => "W3Schools Online Web Tutorials""description" => "w3schools.com""image" => "http://www.w3schools.com/images/colorpicker.png""url" => "https://www.w3schools.com/"]
但是当我试图展示$myarray->title
它时,它给了我错误:
试图获取非对象的属性“标题”
public function showDetail(Request $request){
$rUrl = "http://api.linkpreview.net/?key=5c59318d927ca5c5b481c89a6c18a0a2623a61d568502&q=".$request->body;
$json_string= file_get_contents($rUrl);
$data= json_decode($json_string,true);
return view('showIn')->with('data', $data);
}
预期结果:W3Schools Online Web Tutorials
实际结果:错误:试图获取非对象的属性“标题”
解决方案
您的 JSON 字符串用双引号表示,请使用单引号。
其次,$myarray->title
如果你正在处理一个对象,你会做什么。由于您使用数组,因此请这样做$myarray['title']
这将起作用。
$myjson = '{"title": "W3Schools Online Web Tutorials", "description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}';
$myarray = json_decode($myjson, true);
echo $myarray['title'];
推荐阅读
- python - 如何在div中获取文本
- javascript - highstock 如何表示大于屏幕分辨率的点数?
- c# - 将一个类中的数据传递给另一个类中的函数
- javascript - decode-jpeg2000.js:15 未捕获类型错误:无法读取 decode-jpeg2000.js:15 处未定义的属性“0”
- javascript - 没有处理程序的 addEventListener
- c++ - 如何自定义模板以不包含某些类型
- c++ - MEX C++ 原始数据访问
- java - 是否可以将初始化部分拆分为不同的类?
- sql - SQL - 选择半径中的所有项目
- php - Laravel 一对一多态关系