Jump to content
louisstephens

Adding "object" in from of returned json from "api"

Recommended Posts

So I have been hard at work creating url segments for a template (api) and everything is working swimmingly in creating a simple end point for svelte.js. I have however, run into a few questions that I can wrap my head around.

In my api template I have:

if($input->urlSegment1 === 'clients') {
    header('Content-Type: application/json');


    $clients = $pages->find("template=clients");
    $client_array = array();

    foreach ($clients as $client) {
        $id = $client->id;
        $title = $client->title;
        $url = $client->url;
        $clientName = $client->client_name;
        $clientColor = $client->client_color->value;
        $assigned = $client->assigned_to->user_full_name;


        $client_array[] = array(
            'id' => $id,
            'code' => $title,
            'name' => $clientName,
            'associated_users' => $assigned,
            'url' => $url
        );
    }


    $client_json = json_encode($client_array, true);
    echo $client_json;
}

The output json from this is:

[
    {
        "id":1644,
        "code":"abc",
        "name":"Test Name",
        "associated_users":null,
        "url":"\/pw\/clients\/abc\/"
    },
    {
        "id": 1645,
        "code": "xyz",
        "name": "Test Name",
        "associated_users": null,
        "url": "\/pw\/clients\/xyz\/"
    },
]

I was curious is it possible to add in "clients" before this output json so it would appear as 

clients: [
    {
        "id":1644,
        "code":"abc",
        "name":"Test Name",
        "associated_users":null,
        "url":"\/pw\/clients\/abc\/"
    },
    {
        "id": 1645,
        "code": "xyz",
        "name": "Test Name",
        "associated_users": null,
        "url": "\/pw\/clients\/xyz\/"
    },
]

I was not really sure of how to tackle this in my php code, and have spent more time than I care to admit trying to figure it out. Another question I have is that "associated_users" is returning null, which in this instance is correct. It is a multi page field that is set to pull a custom name field from the users template, ie "Louis Stephens" would be associated with the first page. I understand that I need to use a foreach to get the correct data, but I was really unsure of how to place this inside an array, or update the array with the new data. Any help with any of this would greatly be appreciated.

Share this post


Link to post
Share on other sites
16 minutes ago, louisstephens said:

I was curious is it possible to add in "clients" before this output json so it would appear as 

I believe this would result in erroneous JSON syntax. Your 'clients' need to be a (key or property) element of either an object or an array, not a preceding string.

  • Like 1

Share this post


Link to post
Share on other sites

I believe you are right. I was looking at a file and completely missed that the output was supposed to look like the following:

{
"clients": [
    {
        "id":1644,
        "code":"abc",
        "name":"Test Name",
        "associated_users":null,
        "url":"\/pw\/clients\/abc\/"
    },
    {
        "id": 1645,
        "code": "xyz",
        "name": "Test Name",
        "associated_users": null,
        "url": "\/pw\/clients\/xyz\/"
    },
]
}

 

  • Like 1

Share this post


Link to post
Share on other sites

Yes, you will get it like with this code:

$out = new \stdClass();
$out->clients = [];
foreach([0=>['id'=>'abc'], 1=>['id'=>'xyz']] as $client) {
    $out->clients[] = $client;
}

header('Content-Type: application/json');
echo json_encode($out);

see: https://www.php.net/manual/en/language.types.object.php#118679

 

  • Like 1

Share this post


Link to post
Share on other sites
51 minutes ago, horst said:

Yes, you will get it like with this code:


$out = new \stdClass();
$out->clients = [];
foreach([0=>['id'=>'abc'], 1=>['id'=>'xyz']] as $client) {
    $out->clients[] = $client;
}

header('Content-Type: application/json');
echo json_encode($out);

see: https://www.php.net/manual/en/language.types.object.php#118679

 

A question regarding the formatting here. I know in the example you are assigning the id's from what is typed in the foreach, however, how would you go about doing this programmatically as I am trying to get all the fields from each page? Sorry for my confusion here, just a lot to wrap my head around.

Share this post


Link to post
Share on other sites
$allowed_fields = [
    'title',
    'seo_title'
];

$out = $pages->find('include=all, limit=10')->explode(function($p) use($allowed_fields) {
    $fields = $p->fields;
    foreach($fields as $f) {
        if(in_array($f->name, $allowed_fields)) {
            return [
                'id' => $p->id,
                'title' => $p->title
                ];
        }
    }
});

echo json_encode($out);

 

  • Like 2

Share this post


Link to post
Share on other sites

Thanks zeka, I appreciate the help! I tried your suggestion really quickly this morning and the results are still pretty similar to what I was doing previously:

[{"id":1644,"title":"ABC"},{"id":1648,"title":"DEF"},{"id":1652,"title":"GHI"},{"id":1686,"title":"JKL"}]

However, I did end up "figuring it out" just now by changing my json_encode  to 

    echo json_encode(array("clients" => $clientArray));

(Changed $clients_array to $clientsArray to avoid confusion with my field naming scheme.)

Share this post


Link to post
Share on other sites

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Marvin
      Hello,
      I'm new at process wire and i want to make an web using upload file and showing it at the table as a link to open it at the new tab. I wa succed while upload a file, but how i showing it as a link at the table to open it at the new tab of my browser? Any suggestion may helpfull
      Here i attach my code below :
      This code is for upload it to back-end (process wire)
      <?php $note = $note2 = $hidden =""; if($input->post->submit){ $upload_path = $config->paths->assets.'files/upload/'; if(!is_dir($upload_path)){ if(!wireMkdir($upload_path)) throw new WireException("No upload path"); } $original = $sanitizer->text($input->post->original); $indonesia = $sanitizer->text($input->post->indonesia); $other = $sanitizer->text($input->post->other); $composer = $sanitizer->text($input->post->composer); if(!$original || !$indonesia || !$other || !$composer){ $note = "Data tidak lengkap"; } else { $newFile = new WireUpload("song_files"); $newFile->setMaxFiles(1); $newFile->setOverwrite(false); $newFile->setDestinationPath($upload_path); $newFile->setValidExtensions(array('pdf','docx','doc')); $files = $newFile->execute(); if(!count($files)) { $newFile->error("No files received, so not creating page."); return false; } $newImg = new WireUpload("img_files"); $newImg->setMaxFiles(1); $newImg->setOverwrite(false); $newImg->setDestinationPath($upload_path); $newImg->setValidExtensions(array('jpeg','jpg','png','gif')); $files = $newImg->execute(); if(!count($files)) { $newImg->error("No files received, so not creating page."); return false; } $newPage = new Page(); $newPage->template = "files"; $newPage->parent = $pages->get("/files/"); $newPage->title = $original; $newPage->text_1 = $indonesia; $newPage->text_2 = $other; $newPage->text_3 = $composer; $newPage->of(false); $newPage->save(); foreach($files as $filename) { $filepath = $upload_path . $filename; $newPage->files->add($filepath); $newPage->message("Add file : $filename"); unlink($filepath); } $newPage->save(); } } ?> and this code to showing it as a link at the table
      <table class="border"> <tr> <th>No.</th> <th>Original Song Title</th> <th>Indonesia Song Title</th> <th>Other Song Title</th> <th>Composer</th> <th>File (pdf)</th> </tr> <?php $num = 1; $song; foreach($pages->get("/files/")->children as $child) { //showing every child at files parent directory $page == $child; $song = $pages->get("/files/".$child->id."/")->files; //showing uploaded files at child directory echo $child->id; echo "<tr><td>".$num++.".</td><td>".$child->title."</td><td>".$child->text_1."</td><td>".$child->text_2."</td><td>".$child->text_3."</td><td><a href='".$song->httpUrl."'</a>".$song->name."</td></tr>"; } ?> </table> Thank you for any suggestion
    • By hellerdruck
      Hi all
      I need to export all the texts from a website to a translation company (as json or csv or txt...). How can this be done? Of course manually, but this website is huge and it would take me years...
      Also, as a second step, importing the translation ...
      Any ideas anyone? Tutorials? Plugins?
      Thanks for your help.
    • By picarica
      so i am trying to fetch dimensions of image using getimagesize() but it returns nothing, at least i think so, i want to feed it to data attribute, bit its emtpy, i tried feeding it the image directly or just image->url
      here is my source code

       
      foreach($page->repeat_body as $r_body) { /* other code here*/ if ($r_body->gallery_check == 1) { echo "<div class='my-gallery' id='grid-gallery' itemscope itemtype='http://schema.org/ImageGallery'>"; foreach($r_body->image as $image) { $options = array('quality' => 80, 'upscaling' => true, 'cropping' => 'north', 'sharpening'=>'medium'); $thumb = $image->size(400, 400, $options); $large = $image->size(1280, 0, $options); list($width, $height) = getimagesize($image->url); echo " <figure itemprop='associatedMedia' itemscope itemtype='http://schema.org/ImageObject'> <a href='$large->url' itemprop='contentUrl' data-size='$widthx$height' data-index='0'> <img src='$thumb->url' height='$height' width='$width' itemprop='thumbnail' alt='Beach'> </a> </figure>"; } echo "</div>"; } /* other code here*/ } now, the images are outputted correctly, i can open then and browse them
    • By franciccio-ITALIANO
      Hello to all. I would like to create an app. So I need to learn at least one programming language. I got informed online, and discovered that javascript with node.js, is the revolution of recent years, because it's faster than php. I wonder: if I develop an app with javascript and with a javascript framework (e.g. Meteor), is there a way to integrate processwire work? I know that processwire supports the transformation of the site into an application, but would it be as simple as Meteor? With the Meteor framework I have my app online in 10 minutes, and without even knowing javascript! (Knowing javascript would serve to personalize it). I should then install the app in a SUB-DOMAIN. If I study php, instead, and if I use a php framework (e.g. Laravel), how long does it take to have my first working app? Is it easy to process Laravel's components? Is writing forms for processwire apps with php a very complex job? Is it better to use Meteor and start with javascript? What would you recommend?
    • By Marvin
      Hello, i want to ask, i maintain a website that using a processwire and php, and i want to make an archive at my website using a subfolder system, but when i try,
      the sebfolder is show but when i click the files in that subfolder not show, and my browser just show me an error Invalid argument supplied for foreach(), i don't know why it error
      Here i attach my code and my screenshoot website :
      This is my code

      This is result of my website

      This is my error

       
       
×
×
  • Create New...