简体   繁体   English

How can I convert the json file taken with the api to a javascript object by parsing it with laravel?

[英]How can I convert the json file taken with the api to a javascript object by parsing it with laravel?

I guess I need to use json.parse here but I don't know exactly how to use it.我想我需要在这里使用 json.parse 但我不知道如何使用它。

Userscontroller.php用户控制器.php

 function list(){


$clients = Clients::all();

$result["users"]=$clients;


return $result;

And data:和数据:

{
"users": [
    {
        "id": 1,
        "fullName": "Deniz",
        "company": "Riskomer",
        "role": "editor",
        "username": "denden",
        "country": "Türkiye",
        "contact": "05355141450",
        "email": "hallobro82@gmail.com",
        "currentPlan": "Enterprise",
        "status": "inactive",
        "avatar": ""
    },
   

I need it turned out like this.我需要它变成这样。 In short, I need to convert the json object to javascript object as follows.简而言之,我需要将 json object 转换为 javascript object 如下。 How can I do this with Laravel?如何使用 Laravel 做到这一点?

users: [
{
  id: 1,
  fullName: 'Galen Slixby',
  company: 'Yotz PVT LTD',
  role: 'editor',
  username: 'gslixby0',
  country: 'El Salvador',
  contact: '(479) 232-9151',
  email: 'gslixby0@abc.net.au',
  currentPlan: 'enterprise',
  status: 'inactive',
  avatar: '',
},
$array=array('users'=>Clients::all());
return $array;

If you're trying to append a parameter to each resource, you should use each() and setAttribute() method.如果您尝试将 append 参数传递给每个资源,则应使用each()setAttribute()方法。

$result = \App\Models\Clients::all()
    ->each(function (\App\Models\Clients $client) {
        return $client->setAttribute('testKey', 'testValue');
    });

And in your javascript code, just parse the javascript to convert the json to javascript object type. And in your javascript code, just parse the javascript to convert the json to javascript object type.

JSON.parse('{!! $result !!}')

Notice : Be sure to echo $result with {!! !!}注意:一定要回显$result{!! !!} {!! !!} not with {{ }} to not escape special characters. {!! !!}不与{{ }}不转义特殊字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM