Jump to content

export array to .json format


abe.izar
 Share

Recommended Posts

i am trying to save a page array as a .json string.

i tried:

$values = $pages->find("title=foo");
$jsonFile = wireEncodeJSON($values->getArray());

yet i simply get :

[{},{},{}]

i figured this didn't work becase the array has values which are objects, and they don't get converted properly.

i can probablly go through every child and convert it to an array and bulid the json manually, yet i wonder if there is an easier way to do this.

thanks :D

  • Like 1
Link to comment
Share on other sites

Welcome to the forums abe.izar. Seems like they should make json_encode at least attempt to typecast an object to a string (which would convert to IDs here). Maybe I can update wireEncodeJSON (a front-end to json_encode) do that. However, if you really want to export pages and all their data to JSON, here's how you can do it:

function pagesToJSON(PageArray $items) {
 $a = array();
 foreach($items as $item) {
   $a[] = pageToArray($item); 
 }
 return json_encode($a); 
}

function pageToArray(Page $page) {

 $outputFormatting = $page->outputFormatting;
 $page->setOutputFormatting(false);

 $data = array(
   'id' => $page->id,
   'parent_id' => $page->parent_id,
   'templates_id' => $page->templates_id,
   'name' => $page->name,
   'status' => $page->status,
   'sort' => $page->sort,
   'sortfield' => $page->sortfield,
   'numChildren' => $page->numChildren,
   'template' => $page->template->name,
   'parent' => $page->parent->path,
   'data' => array(),
   );

 foreach($page->template->fieldgroup as $field) {
   if($field->type instanceof FieldtypeFieldsetOpen) continue;
   $value = $page->get($field->name); 
   $data['data'][$field->name] = $field->type->sleepValue($page, $field, $value);
 }

 $page->setOutputFormatting($outputFormatting);

 return $data;
}
  • Like 7
Link to comment
Share on other sites

  • 3 weeks later...

Hi,

Thanks Ryan, for this snippet. I'll be using it all over in a web app I'm building using PW.

I've tried to make it into a module, but am running into an issue I confess I don't understand.

Could someone who knows the guts of modules in PW more than I take a look at what I've got so far?

The error I get is:

Method PageArray::toJSON does not exist or is not callable in this context (in /Projects/MyAppFolder/wire/core/Wire.php line 231)

Thanks!

Link to comment
Share on other sites

In your getModuleInfo() method, delete the "'permanent' => true" line, as that only makes it impossible to uninstall the module (which we only want for select core modules).

In your init() method, you are adding a 'toJSON' method to the $pages API variable. But your pagesToJSON() method appears to be written like it's meant to interact with a PageArray. As a result, I think the problem is that you need to change your hook like in the init() method to be this:

$this->addHook('PageArray::toJSON', $this, 'pagesToJSON');

I am guessing that the source if the error is that you are trying to call toJSON() on a PageArray when it's not hooked there. Hopefully the above change should fix it.

Link to comment
Share on other sites

Yes, Ryan you nailed it. I fixed that up (and also another small fix to how I called the pageToArray function) and it's good to go.

Do you still prefer that we offer new modules up via a forum post, or is there another way?

Thanks for your as always excellent help :)

Link to comment
Share on other sites

Do you still prefer that we offer new modules up via a forum post, or is there another way?

Forum post for now, but that's short term. We'll be having a more official modules directory here soon. I plan to manually take everything from the forum to populate the modules directory initially.

Link to comment
Share on other sites

  • 1 year later...

Hi all! Also new here.

Also my first time meddling with modules and it seems I can't make it to work. I 'called' it inside a template page (implemented it as a module from: https://gist.github.com/evanmcd/3080802):

include("./head.inc");

$values = $pages->find("title=starter");
$xxx = new PagesToJSON();
echo $xxx->pagesToJSON($values);

include("./foot.inc");

resulting to this error:
 

Error: Exception: Item 'return' set to PageArray is not an allowed type (in D:\xampp\htdocs\pw2\wire\core\WireArray.php line 300)

#0 D:\xampp\htdocs\pw2\wire\core\PageArray.php(192): WireArray->set('return', '[]')
#1 D:\xampp\htdocs\pw2\wire\core\WireArray.php(322): PageArray->set('return', '[]')
#2 D:\xampp\htdocs\pw2\site\modules\PagesToJSON.module(60): WireArray->__set('return', '[]')
#3 D:\xampp\htdocs\pw2\site\templates\starter.php(14): PagesToJSON->pagesToJSON(Object(PageArray))
#4 D:\xampp\htdocs\pw2\wire\core\TemplateFile.php(140): require('D:\xampp\htdocs...')
#5 [internal function]: TemplateFile->___render()
#6 D:\xampp\htdocs\pw2\wire\core\Wire.php(359): call_user_func_array(Array, Array)
#7 D:\xampp\htdocs\pw2\wire\core\Wire.php(317): Wire->runHooks('render', Array)
#8 D:\xampp\htdocs\pw2\wire\modules\PageRender.module(337): Wire->__call('render', Array)
#9 D:\xampp\htdocs\pw2\wire\modules\PageRender.module(337): TemplateFile->render()
#10 [internal function]: PageRender->___renderPage(Object(HookEvent)

Thanks!

Link to comment
Share on other sites

  • 3 weeks later...

Welcome to the forums abe.izar. Seems like they should make json_encode at least attempt to typecast an object to a string (which would convert to IDs here). Maybe I can update wireEncodeJSON (a front-end to json_encode) do that. However, if you really want to export pages and all their data to JSON, here's how you can do it:

function pagesToJSON(PageArray $items) {
  $a = array();
  foreach($items as $item) {
    $a[] = pageToArray($item); 
  }
  return json_encode($a); 
}

function pageToArray(Page $page) {

  $outputFormatting = $page->outputFormatting;
  $page->setOutputFormatting(false);

  $data = array(
    'id' => $page->id,
    'parent_id' => $page->parent_id,
    'templates_id' => $page->templates_id,
    'name' => $page->name,
    'status' => $page->status,
    'sort' => $page->sort,
    'sortfield' => $page->sortfield,
    'numChildren' => $page->numChildren,
    'template' => $page->template->name,
    'parent' => $page->parent->path,
    'data' => array(),
    );

  foreach($page->template->fieldgroup as $field) {
    if($field->type instanceof FieldtypeFieldsetOpen) continue;
    $value = $page->get($field->name); 
    $data['data'][$field->name] = $field->type->sleepValue($page, $field, $value);
  }

  $page->setOutputFormatting($outputFormatting);

  return $data;
}

This looks like what I need. How would I incorporate a $pages->find("selector") into this?

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

I am trying to use an Event Calendar plugin that needs json input. The supplies js links to a json file but I want to parse the json data straight into the js function as variable jsonEvents.

$(document).ready(function() {
$("#eventCalendarDefault").eventCalendar({
eventsjson: events.json // link to events json
eventsjson: jsonEvents;
});
});

The required json format is:

[ { "date": "1409389200000", "type": "meeting", "title": "Test Project C Brainstorming", "description": "Lorem Ipsum dolor set", "url": "http://www.event7.com/" },
{ "date": "1407862800000", "type": "meeting", "title": "Test Project C Closing", "description": "Lorem Ipsum dolor set", "url": "http://www.event7.com/" },
{ "date":"1407862800000","type": "liason","title":"Crai Film Club - The Great Gatsby","description":"Meeting C", "url": "http://www.event7.com/" } ]

Any help greatly appreciated.

Link to comment
Share on other sites

This looks like what I need. How would I incorporate a $pages->find("selector") into this?

$events = $pages->find("template=sectionItem, parent=1025|1066|1073|1069|1013|1247|1101, sort=startTime, start=10, limit=3");
I am trying to use an Event Calendar plugin that needs json input. The supplies js links to a json file but I want to parse the json data straight into the js function as variable jsonEvents.
$(document).ready(function() {
$("#eventCalendarDefault").eventCalendar({
eventsjson: events.json // link to events json
eventsjson: jsonEvents;
});
});
The required json format is:
[ { "date": "1409389200000", "type": "meeting", "title": "Test Project C Brainstorming", "description": "Lorem Ipsum dolor set", "url": "http://www.event7.com/" },
{ "date": "1407862800000", "type": "meeting", "title": "Test Project C Closing", "description": "Lorem Ipsum dolor set", "url": "http://www.event7.com/" },
{ "date":"1407862800000","type": "liason","title":"Crai Film Club - The Great Gatsby","description":"Meeting C", "url": "http://www.event7.com/" } ]
Any help greatly appreciated.
I'm still struggling with this. It should be simple but I'm going round in circles.
$events = $pages->find("template=sectionItem, parent=1025|1066|1073|1069|1013|1247|1101, sort=startTime, start=10, limit=3");
foreach ($events as $event) {
$start = "".date(strtotime($event->startTime))."";
$title = $event->title;
$arr = array(
'title' => $title, 
'date' => $start
);
    echo $data = json_encode($arr, true);
}
 

Which gives the following output:

{"title":"Llywel Church open days","date":"1370707200"}{"title":"Ladies Night Out","date":"1371250800"}{"title":"Trecastle Knitting Club","date":"1371681000"}
The bit I am stuck on it to get to this. [ ] round the complete data set and each { } separated by a comma except the last one.
[{"title":"Llywel Church open days","date":"1370707200"}, {"title":"Ladies Night Out","date":"1371250800"}, {"title":"Trecastle Knitting Club","date":"1371681000"}]
This  will all be in a script (template). Any help will be greatly appreciated.
Link to comment
Share on other sites

This should help:

$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;

The reason is because before, you are simply json_encoding one PHP array at a time into a native javascript object. This way, you are creating the eventual array of objects - first in PHP, and then asking json_encode to work on the whole collection of items.

  • Like 6
Link to comment
Share on other sites

  • 2 weeks later...
function pagesToJSON(PageArray $items) {
  $a = array();
  foreach($items as $item) {
    $a[] = pageToArray($item); 
  }
  return json_encode($a); 
}

function pageToArray(Page $page) {

  $outputFormatting = $page->outputFormatting;
  $page->setOutputFormatting(false);

  $data = array(
    'id' => $page->id,
    'parent_id' => $page->parent_id,
    'templates_id' => $page->templates_id,
    'name' => $page->name,
    'status' => $page->status,
    'sort' => $page->sort,
    'sortfield' => $page->sortfield,
    'numChildren' => $page->numChildren,
    'template' => $page->template->name,
    'parent' => $page->parent->path,
    'data' => array(),
    );

  foreach($page->template->fieldgroup as $field) {
    if($field->type instanceof FieldtypeFieldsetOpen) continue;
    $value = $page->get($field->name); 
    $data['data'][$field->name] = $field->type->sleepValue($page, $field, $value);
  }

  $page->setOutputFormatting($outputFormatting);

  return $data;
}

Hello Ryan,

thank you for this function!

I'm using it with PW2.4.11 and get a PHP Notice:

Notice: Undefined property: Page::$templates_id in /var/www/pwbootstrap3/wire/core/Page.php on line 604

When I uncomment the line 'templates_id' => $page->templates_id, the notice is gone.

Has anything regarding $templates_id changed in the current dev version?

Cheers

Gerhard

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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...