thmsnhl

Clean way to output data as json

7 posts in this topic

Hi everyone,

I've recently hired at a new company and here I am evaluating the abilities of ProcessWire for our projects.
I was able to meet almost every requirement so far, but there is one point I couldn't find an adequate solution for: outputting data to json.

I am aware of modules like https://modules.processwire.com/modules/pages2-json/ (which does not seem to work for me) but I thought with a function like wireEncodeJSON this should be much cleaner. What I would like to achieve is outputting pages with according field values into an array to use this within javascript.
My first attempt on this was:

$jsontestOne = $pages->find(1001)->children();
echo wireEncodeJSON($jsontestOne);

which outputs 

[{}]

and afterwards I tried that one:

$jsontest = $pages->find("template=basic-page")->getArray();
echo wireEncodeJSON($jsontest);

which outputs 

[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},...]

Maybe you can point out where my mistake is.
 

Thanks in advance!

Share this post


Link to post
Share on other sites

Hi @thmsnhl

Have you seen this thread? 

There is an example that you may find useful

$events = $pages->find("template=sectionItem, parent=1025|1066|1073|1069|1013|1247|1101, sort=startTime, start=10, limit=3");
$events_array = array();

foreach ($events as $event) {
    
    $start = "".date(strtotime($event->startTime))."";
    $title = $event->title;
    
    $events_array[] = array(
        'title' => $title, 
        'date' => $start
    );
}

$events_json = json_encode($events_array, true);
echo $events_json;

 

Share this post


Link to post
Share on other sites

the problem is that you have an array, but the items in the array are \ProcessWire\Page objects, so those can't directly map to a json encode.

you probably need to cycle through the pages you want and create the array manually. Alternately you could have a look at the GraphQL module, which i think some devs are using to get json data to the frontend.

3 people like this

Share this post


Link to post
Share on other sites

Thank you @Zeka for this thread I just realized that I had this already open in a tab but waaaaaay too far on the right hand side of the window, I will try to fit the example in to my project.
But first I will have a look into GraphQL because this might also help me with future requirements. 

Share this post


Link to post
Share on other sites

For simple json outputs, you can use WireArray::explode and json_encode() or wireEncodeJSON() methods

https://processwire.com/api/ref/wire-array/explode/

$myPages = $pages->find('template=basic-page');
// extract required fields into plain array
$data = $myPages->explode(['title', 'created']);
echo wireEncodeJSON($data);
6 people like this

Share this post


Link to post
Share on other sites

For more advanced uses (api or even json-api by specification) I'd recommend something like fractal.

2 people like this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By bmacnaughton
      I have a hook that creates a page for a subset of the pages on our site. It uses the saved page's name as part of the created page's name.
      The problem I am having is that my hook, attached to Pages::saved(), is being called even when the page save failed because of missing fields. Is there a way I can tell that the page save failed due to missing fields?
       
      Never mind - it does succeed; it just issues warnings about required fields.
       
    • By Harmen
      Hi folks,
       
      On the website I am working on I do have a form which needs to be filled in (duh) and when the user clicks on download, the data is send with ajax and processed in the same file by using the ProcessWire API with $config->ajax;
      The data which is provided by the user will be checked with data in my database. If the data is correct I want to push a file download. But this is not working at the moment. It seems like the content of the (.exe) file is pasted in the console instead of pushing the file. My code looks like this:
      if ($config->ajax){ $serial = $input->post('serial'); $DB = DB(); $query = $DB->prepare("/*My query here*/"); $query->bindParam("comparision", $serial, PDO::PARAM_STR); $query->execute(); $reply = ''; $SN_rows = $query->rowCount(); if (!$SN_rows > 0) { $reply = 'error'; } else { $reply = 'success'; $installer = $page->attachments->eq(1); $filename = "Filename"; $filepath = $installer->filename; $options = array( 'forceDownload' => true, 'exit' => true, 'downloadFilename' => $filename ); wireSendFile($filepath, $options); } echo $reply; exit(); } What am I doing wrong here or is it a bug? Is there another way to do this with the processwire API?
       
      Thanks in advance,
       
      ~Harmen
    • By nbcommunication
      Hi,
      I'm sure this is maybe in the works already, given that findMany() is a recent addition to the API, but having this (and the other new find options) available to $users would be a great addition.
      Cheers,
      Chris
      NB Communication
       
    • By laban
      Has anyone integrated Directus with ProcessWire? I have a database in Directus that I want to sync with ProcessWire (create/update/delete pages). But I don't not know where to start. It might be possible with ProcessWire's API in some way?
    • By bmacnaughton
      When a PageTable field in a specific template is being edited I need to know the Page that contains the PageTable so I can fill in hidden fields in the PageTable.
      I can capture the page being edited via:
      // $this->addHookBefore('ProcessPageEdit::execute', ... public function pageEditExecuteBefore(HookEvent $e) { $p = $e->object->getPage(); if ($p->template !== 'rtw-product') return; // $p is the page being edited } I can intercept PageTable entry being saved:
      // $this->addHookBefore('Pages::save' public function savePageBefore (HookEvent $e) { $p = $this->wire('page')->id; $page = $e->arguments('page'); $obj = $e->object; $name = $page->name; // page name of PageTable page $template = $page->template->name; // template of PageTable page $parent = $page->parent->name; // parent directory for PageTable items What I am trying to find is the page in which the PageTable field is located.
      I've also tried having pageEditExecuteBefore() saving $p in $this->context and then accessing that in savePageBefore() but it's a different instance of the class because $this->context is null when it gets to savePageBefore(). I could save the page ID in session, but that seems error prone.
      Does anyone know how to achieve this?