Create single level JSON array

Hello, is it possible to simplify JSON data into the same level array like this example:

{
    "url": [
        "http:\/\/image1.jpg",
        "http:\/\/image2.jpg",
        "http:\/\/image3.jpg",
        "http:\/\/image4.jpg"
    ]
}

My current .json file looks like this:

<?php
$data = $pages->find('images')->images();
foreach($data as $file) {
  $json[] = array(
    'url'   => $file->url(),
  );
}
echo json_encode($json);

which is giving me data like this:

[
 {"url":"http:\/\/image1.jpg"},
 {"url":"http:\/\/image2.jpg"},
 {"url":"http:\/\/image3.jpg"},
 {"url":"http:\/\/image4.jpg"}
]

Should be something like this:

<?php
$data = $pages->find('images')->images();
$urls = [];
foreach($data as $file) {
  $urls[] = $file->url();
}

$json['url'] = $urls;
echo json_encode($json);
1 Like

Perfect! Thank you :grin:

Hi again :blush:

How about with the same thing with children page titles?

<?php

$data = $pages->find('words')->children();
$urls = [];
foreach($data as $file) {
  $urls[] = $file->title();
}

$json['title'] = $urls;

echo json_encode($json);

is giving me:

{
  "title": [
    {
      "value": "page title 1"
    },
    {
      "value": "page title 2"
    },
    {
      "value": "page title 3"
    },
  ]
}

but Iā€™d like

{
    "title": [
        "page title 1",
        "page title 2",
        "page title 3",
    ]
}

What is the $urls? Can that be anything? Thanks very much for your help

I got it! Added (string) before $file->title();

$file->title()->value()

1 Like

Exactly, you need a string. While $file->url() returns a string, $file->title() returns a field object. As @bnomei pointed out above, you can get the string value from a field using the value() method. It is actually preferable to use this method over a simple casting to string.

1 Like