Jump to content

Clean way to output data as json


thmsnhl
 Share

Recommended Posts

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!

Link to comment
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;

 

Link to comment
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.

  • Like 4
Link to comment
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. 

Link to comment
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
 Share

×
×
  • Create New...