Parse json array without value in php - php

I wonder how to parse a json array without values
Json: {"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}
How can i get the value of email in a foreach loop?
What i mean with "without value" is: there is an array called email and name... How can i get the value for "email" that currently says NOT_UNIQUE?

In your current example, your JSON string is malformed. I dont know if thats a typo on your part while creating your question. Assuming the JSON string is okay in your code, a simple json_decode() will do just fine. Consider this example:
$json_string = '{ "Json": { "status": "FAILED", "errors": { "email": [ "NOT_UNIQUE" ], "name": [ "TOO_SHORT" ] } }}';
$data = json_decode($json_string, true);
echo $data['Json']['errors']['email'][0]; // NOT UNIQUE

use json_decode, json_decode($str, true) will return it as an assosiative array whereas json_decode($str, false) will return objects.
json_decode("{"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}", true)['errors']['email']
should get the email for you.

Related

PHP - JSON returning null with different objects

I have two different set of json object as follows.
'{
"eventos": [
{"Event":"QueueParams","Queue":"755","Max":"0","Strategy":"fewestcalls","Calls":"0","Holdtime":"19","TalkTime":"491","Completed":"89","Abandoned":"4","ServiceLevel":"0","ServicelevelPerf":"0.0","Weight":"0","ActionID":"4152750549"},
{"Event":"QueueMember","Queue":"755","Name":"PJSIP/428","Max":"","Location":"PJSIP/428","StateInterface":"PJSIP/428","Membership":"dynamic","Penalty":"0","CallsTaken":"2","LastCall":"1607350581","Status":"2","Paused":"0","ActionID":"4152750549"},
]
}';
$response = json_decode($response);
dd($response);
The problem is, it returns null output.
I want to get json result displayed with different objects. What changes are needed here so that I can display output of different objects ?
Your JSON have a syntax error. Just remove the comma right after the last { ActionID":"4152750549"},.
It have to be like this:
'{
"eventos": [
{"Event":"QueueParams","Queue":"755","Max":"0","Strategy":"fewestcalls","Calls":"0","Holdtime":"19","TalkTime":"491","Completed":"89","Abandoned":"4","ServiceLevel":"0","ServicelevelPerf":"0.0","Weight":"0","ActionID":"4152750549"},
{"Event":"QueueMember","Queue":"755","Name":"PJSIP/428","Max":"","Location":"PJSIP/428","StateInterface":"PJSIP/428","Membership":"dynamic","Penalty":"0","CallsTaken":"2","LastCall":"1607350581","Status":"2","Paused":"0","ActionID":"4152750549"}
]
}';
For any Json problem, run a json_last_error() right after the decode.
For example, to show each ActionID;
<?php
$rawJson = '{"eventos": [{"Event":"QueueParams","Queue":"755","Max":"0","Strategy":"fewestcalls","Calls":"0","Holdtime":"19","TalkTime":"491","Completed":"89","Abandoned":"4","ServiceLevel":"0","ServicelevelPerf":"0.0","Weight":"0","ActionID":"4152750549"}, {"Event":"QueueMember","Queue":"755","Name":"PJSIP/428","Max":"","Location":"PJSIP/428","StateInterface":"PJSIP/428","Membership":"dynamic","Penalty":"0","CallsTaken":"2","LastCall":"1607350581","Status":"2","Paused":"0","ActionID":"4152750549"} ] }';
$json = json_decode($rawJson);
$eventos = $json->eventos;
foreach ($eventos as $event) {
echo $event->ActionID . PHP_EOL;
}
Note: There was an trailing comma (,) behind the last event object, I've removed it to make it valid JSON.
Try it online!

Get JSON Data From .json (php)

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php

How to correctly parse JSON in PHP

I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id

JSON array parsing in PHP

please help me how to parse following JSON in PHP.
I got following JSON using PIWIK reporting api. How do I get PageTitle from following json in PHP. I tried following code for JSON parsing.
$json = '[
{
"idSite": "1",
"idVisit": "84",
"visitorId": "f08dc1f2a3e1f839",
"visitorType": "returning",
"visitorTypeIcon": "plugins/Live/images/returningVisitor.gif",
"visitConverted": "0",
"visitConvertedIcon": null,
"visitEcommerceStatus": "none",
"visitEcommerceStatusIcon": null,
"searches": "0",
"events": "4",
"actions": "9",
"actionDetails": [
{
"type": "action",
"url": "http://mywwebsiteurl.com",
"pageTitle": "PageTitle",
"pageIdAction": "110"
}
]
}
]';
$visits = json_decode($json, true);
foreach ($visits->actionDetails as $data) {
echo $data->pageTitle;
}
I got following notice
Notice: Trying to get property of non-object
How to get pageTitle from above JSON.
It should be :-
$visits = json_decode($json, true);
foreach ($visits[0]["actionDetails"] as $data) {
echo $data["pageTitle"];
}
You set second attribute to TRUE - so according to the manual.
"When TRUE, returned objects will be converted into associative arrays."
Try using the array aproach
foreach ($visits['actionDetails'] as $data){
echo $data['pageTitle'];
}
As documented in the manual, and mentioned by Matt, the second parameter of json_decode() controls the return type. If it is omitted or set to false (the default) then an object is returned. If it is set to true an array is returned.
Your code, json_decode($json, true);, will return an array but you then try to use the array as an object.

how to decode json sting including array and object in PHP?

I want to decode json string including array and object in PHP. When i decoded with
$array = json_decode($json, true);
print_r($array);
it return NULL. Let me know, the way to decode json in PHP. This is my json string.
{
success: 1,
message: "Successful!",
save_date: "2013-09-11 04:09:26",
test: [
{
test_id: "1",
test_date: "2013-09-12",
test_name: "Test 1"
},
{
test_id: "2",
test_date: "2013-09-11",
test_name: "Test 2"
}
]
}
That's not a valid JSON object. JSON objects must enclose all property names in double quotes:
{ "success": 1, "message": "Successful!" }
PHP provides the handy json_last_error_msg function to tell you that.
There's also the online tool JSONLint to validate JSON strings.
Your JSON is invalid, the property names need to be in quotes too.
Like this:
{
"success": 1,
"message": "Successful!",
"save_date": "2013-09-11 04:09:26",
"test": []
}
Hint: use JSONLint to validate your JSON.
your json string should be like the following :
$sJson = '{"success": 1,"message": "Successful!","save_date": "2013-09-11 04:09:26",
"test": [ {"test_id": "1","test_date": "2013-09-12","test_name": "Test 1"},
{"test_id": "2","test_date": "2013-09-11","test_name": "Test 2"}]}';
Use this
$result=(array)json_decode('your json string');
I think it's working for you

Categories