I am having issues with validating the output of my json_encode() function.
I am pulling in an XML feed with cURL, converting it into an array, and converting that array into JSON with json_endode(). Ill spare you the cURL stuff:
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json = str_replace('\/','/',json_encode($article));
echo $json;
}
Which is giving me a JSON readout of:
{
"articleResult": {
"articleId": "0001",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
{
"articleResult": {
"articleId": "0002",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
This will give me a JSONLint error saying:
Parse error on line 10:
..._120x80.jpg" }}{ "articleResult
---------------------^
Expecting 'EOF', '}', ',', ']'
So naturally I will add in the comma, which gives me an End of File expectation:
Parse error on line 10:
..._120x80.jpg" }},{ "articleResu
---------------------^
Expecting 'EOF'
I am new to JSON, but I have checked the website and a few resources for proper JSON formatting and structure, and from what I can see my readout is following the guidelines. Any pointers?
Resources I've checked:
JSON.org naturally
Wikipedia has well documented page
W3Resource Had a good explanation of structure.
JSONLint
You were encoding 2+ objects into json string, you need [ ] to wrap them
the correct syntax is
[
{ /* first object */ }
, { /* second object */ }
, { /* third object */ }
]
the things you need to look out are
[ ] wrap
separate objects by comma
Solution
$json = array();
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json[] = $article;
}
echo json_encode($json);
Related
I know that probably is better to save new objects at the end of an existing array with no name, but I would like to complicate things a little to learn how to do it, and add new object at the index value [0] instead of the end [arr.length - 1] of an array, also I need to save it inside an specific array name because I will have more than one in this sample. The information is collected by an html form.
What I have is:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$file_name='newsFeeder'. '.json';
if(file_exists("./feeder/{$file_name}")) {
$current_data=file_get_contents("./feeder/{$file_name}");
$array_data=json_decode($current_data, true);
$extra=array(
'year' => $_POST['year'],
'link' => $_POST['link'],
'img' => $_POST['img'],
);
$array_data[]=$extra;
echo "file exist<br/>";
return json_encode($array_data, JSON_PRETTY_PRINT);
}
else {
$datae=array();
$datae[]=array(
'year' => $_POST['year'],
'link' => $_POST['link'],
'img' => $_POST['img'],
);
echo "file not exist<br/>";
return json_encode($datae, JSON_PRETTY_PRINT);
}
}
$file_name='newsFeeder'. '.json';
if(file_put_contents("./feeder/{$file_name}", get_data())) {
echo 'success';
}
else {
echo 'There is some error';
}
}
?>
and the result is a JSON file like this:
[
{
"year": "2022",
"link": "xxxxxx_01.html",
"img": "xxxxxx_01.webp"
},
{
"year": "2023",
"link": "xxxxxx_02.html",
"img": "xxxxxx_02.webp"
},
.
.
.
.
{ // <- This is the newest object added at index value [arr.length - 1] //
"year": "2024",
"link": "xxxxxx_03.html"
}
]
But what I want to achieve is this:
{
"newsFeeder": [ // <- this is the array where I need to add new objects to //
{ // <- This is the newest object added at index value [0] //
"year": "2024",
"link": "xxxxxx_06.html",
"img": "xxxxxx_06.webp"
},
.
.
.
.
{
"year": "2023",
"link": "xxxxxx_02.html",
"img": "xxxxxx_02.webp"
},
{
"year": "2022",
"link": "xxxxxx_01.html",
"img": "xxxxxx_01.webp"
}
],
"whyComplicate_things":[ // I need to let this array untouched //
{"a":"01.webp", "title":"title 01"},
{"a":"02.webp", "title":"title 02"},
{"a":"03.webp", "title":"title 03"}
]
}
I tried different approach but those only erase everything and add only the one with the info collected, or ending breaking things up. Help to learn how to achieve this is appreciated!
You can achieve this with array_unshift. It moves all array elements +1, and inserts the second parameter of the function call on index 0.
array_unshift($array_data, $extra);
To add to the beginning of the array, you can append with , ...$array_name if using PHP > 7.4
Something like this:
$array_name = [array(
'year' => $_POST['year'],
'link' => $_POST['link'],
'img' => $_POST['img']
), ...$array_name];
My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.
I have a JSON file stored on my server that I need to add data to. I have successfully retrieved the file into memory and have parsed it successfully. I am just having a hard time placing the new JSON data in the correct spot.
Here is the format of my JSON file:
{
"emails": [
{
"group": "1st Group",
"list": [
{
"id": 1,
"subject": "Testing 1"
},
{
"id": 2,
"subject": "Testing 2"
}
] // End list array
}, // End 1st Group
{
"group": "2nd Group",
"list": [
{
"id": 3,
"subject": "Testing 3"
},
{
"id": 4,
"subject": "Testing 4"
}
] // End list array
} // End 2nd Group
/* NEED TO INSERT NEW DATA HERE */
] // End emails array
}
I am trying to append a new group list after the last group list. In this example, that would be after this line: } // End 2nd Group.
Here is my PHP code which gets the JSON file from my server and parses it:
$getJSON = file_get_contents('emails.json');
$tempArray = json_decode($getJSON, true);
$numberOfGroups = count($tempArray['emails'][0]);
And here is my php code that creates the format/layout of my JSON file:
$groupArray = array();
$json = array( 'emails' => array() );
foreach ($contextIORequest->getData() as $message) {
$newTZ = new DateTimeZone("America/Chicago");
$currentTime = new DateTime();
$currentTime = DateTime::createFromFormat('U', $message['date_received']);
$currentTime->setTimezone($newTZ);
$formattedDateReceived = $currentTime->format('F j, Y');
if (!in_array($formattedDateReceived, $groupArray)) {
array_push( $json['emails'],
array(
'group' => $formattedDateReceived,
'list' => array()
)
);
$groupArray[] = $formattedDateReceived;
}
$body = str_replace(array("\r\n","\n"),"", $message['body'][0]['content']);
$newBody = preg_replace('!\s+!', ' ', $body);
array_push($json['emails'][array_search($formattedDateReceived,$groupArray)]['list'],
array(
'id' => $message['message_id'],
'subject'=> addslashes($message['subject']),
'to' => array("Me"),
'body' => $newBody,
'time' => $formattedDateReceived,
'datetime' => $formattedDateReceived,
'from' => $message['addresses']['from']['name'],
'dp' => "assets/img/profiles/avatar.jpg",
'dpRetina' => "assets/img/profiles/avatar2x.jpg"
)
);
} // end foreach loop
// Output the JSON
header('Content-Type: application/json');
echo json_encode($json);
So how would I go about appending a new group list after the last group list? And this needs to be done without actually included the emails array used to create the JSON.
After running json_decode on the serialized data (with the second param passed as true like you've done), you'll have, in PHP, an associative array which has one element at a key named emails. That element is an array and holds the group lists to which you want to add another. So it's a matter of:
$data = json_decode($getJSON, true);
$data['emails'][] = $TheNewGroupList;
Don't let the fact that it started as serialized data in JSON format get you frazzled. Once you've run json_decode it's just a PHP data structure (object or array), and operations on it are just like any other PHP data.
I know this question was asked already for couple times, I've seen the answers but it already helped me a lot, but i need to solve one more problem regarding to this.
So the question is:
I need to build json file with php.
Here how looks my json file that i need:
{
"fashion":[
{
"alt":"Alisa",
"src":"img/fashion/Alisa/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum001",
"itemNum":0,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa1.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa5.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa7.jpg"
}
]
},
{
"alt":"2-Addis",
"src":"img/fashion/2-Addis/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum002",
"itemNum":1,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/2-Addis/addis1.jpg"
},
{
"alt":"albumImg4",
"src":"img/fashion/2-Addis/addis4.jpg"
}] } ] }
and so on...
I can't find out how to make a list of images inside each album
This is a php function a have
function buildJson(){
$json = json_encode(array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
"album"=>array(
"src"=>"img/fashion/Alisa/alisa1.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa5.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa7.jpg",
),
)
));
echo $json;
}
but I get json like this one:
{
"Fashion": {
"0": {
"src": "img/fashion/Alisa/alisa2.jpg"
},
"1": {
"src": "img/fashion/Alisa/alisa3.jpg"
},
"alt": "Alisa",
"src": "img/fashion/Alisa/kubik.jpg",
"id": "FashionAlbum001",
"itemNum": "0",
"album": {
"src": "img/fashion/Alisa/alisa1.jpg"
}
}
}
How is it possible to fix it?
Thank you!
Please pay more attention to the code you're writing :) Try to decode correct version of your json file and compare it to one you wrote. You should see some differences.
Your problem ir what follows after album key. You are assigning array with only one value to it instead of assigning array of arrays.
This is the way to go:
"album" => array(
array("src" => "img/fashion/Alisa/alisa1.jpg"),
array("src" => "img/fashion/Alisa/alisa5.jpg"),
array("src" => "img/fashion/Alisa/alisa7.jpg"),
),
you trouble in nesting album array
fixed code
function buildJson(){
$json = json_encode(
array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
// nesting error here
"album"=> array(
array("src"=>"img/fashion/Alisa/alisa1.jpg"),
array("src"=>"img/fashion/Alisa/alisa5.jpg"),
array("src"=>"img/fashion/Alisa/alisa7.jpg")
)
)
)
);
echo $json;
}
I know how to decode a JSON string with one object with your help from this example How to decode a JSON String
But now I would like to improve decoding JSON string with several objects and I can't understand how to do it.
Here is an example:
{ "inbox": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"sent": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"draft": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
How to make just one foreach() to
decode above JSON string?
How to detect object's names: inbox,
sent or draft on this foreach()?
New answer
Re your revised question: foreach actually works with properties as well as with many-valued items (arrays), details here. So for instance, with the JSON string in your question:
$data = json_decode($json);
foreach ($data as $name => $value) {
// This will loop three times:
// $name = inbox
// $name = sent
// $name = draft
// ...with $value as the value of that property
}
Within your main loop over the properties, you can use an inner loop to go over the array entries each property points to. So for instance, if you know that each of the top-level properties has an array value, and that each array entry has a "firstName" property, this code:
$data = json_decode($json);
foreach ($data as $name => $value) {
echo $name . ':'
foreach ($value as $entry) {
echo ' ' . $entry->firstName;
}
}
...will show:
inbox:
Brett
Jason
Elliotte
sent:
Issac
Tad
Frank
draft:
Eric
Sergei
Old answer(s)
Begin edit
Re your comment:
Now I would like to know how to decode JSON string with several objects!
The example you posted does have several objects, they're just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:
{"name": "I'm the first object"},
{"name": "I'm the second object"}
That JSON is not valid. There has to be a single top-level object. It might just contain an array:
{"objects": [
{"name": "I'm the first object"},
{"name": "I'm the second object"}
]}
...or of course you can give the individual objects names:
{
"obj0": {"name": "I'm the first object"},
"obj1": {"name": "I'm the second object"}
}
End edit
Your example is one object containing three properties, the value of each of which is an array of objects. In fact, it's not much different from the example in the question you linked (which also has an object with properties that have array values).
So:
$data = json_decode($json);
foreach ($data->programmers as $programmer) {
// ...use $programmer for something...
}
foreach ($data->authors as $author) {
// ...use $author for something...
}
foreach ($data->musicians as $musician) {
// ...use $musician for something...
}
You can use the json_decode function to decode the JSON string :
$json = <<<JSON
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
JSON;
$data = json_decode($json);
Then, to see what the data looks like, you can dump it :
var_dump($data);
And you'll see you have an object containing three arrays, each one containing other sub-objects :
object(stdClass)[1]
public 'programmers' =>
array
0 =>
object(stdClass)[2]
public 'firstName' => string 'Brett' (length=5)
public 'lastName' => string 'McLaughlin' (length=10)
1 =>
object(stdClass)[3]
public 'firstName' => string 'Jason' (length=5)
public 'lastName' => string 'Hunter' (length=6)
...
public 'authors' =>
array
0 =>
object(stdClass)[5]
public 'firstName' => string 'Isaac' (length=5)
public 'lastName' => string 'Asimov' (length=6)
...
Which means you know how to access your data.
For example, to display the list of the programmers, you could use :
foreach ($data->programmers as $programmer) {
echo $programmer->firstName . ' ' . $programmer->lastName . '<br />';
}
Which would get you the following output :
Brett McLaughlin
Jason Hunter
Elliotte Harold