PHP json_decode showing null while parsing JSON - php

I am trying to parse JSON data but while json_decode() the var_dump() shows the value as null. Below is my program:
<?php
$json='_variable_1461092903017=[ {
message:"success",
data1:{
datalist:[
{field1:"value1",field2:"value2"} ,
{field1:"value1",field2:"value2"} ,
{field1:"value1",field2:"value2"}
]
},
data2:[ {
Date:"20 Apr 2016",
details:[
{Code:"123",name:"xyz"},
{Code:"456",name:"abc"},
],
},
{
Date:"21 Apr 2016",
details:[
{Code:"123",name:"xyz"},
{Code:"456",name:"abc"},
],
},
{
Date:"22 Apr 2016",
details:[
{Code:"123",name:"xyz"},
{Code:"456",name:"abc"},
],
}
]}
]';
$json_data = json_decode($json);
var_dump($json_data);
?>

Like others said that is not valid JSON
you can debug it using a JSON Linter http://jsonlint.com
A cool valid JSON railroad diagram:
http://www.json.org
This should be what you are looking for (I didn't execute it):
<?php
$json='[{
"message" :"success",
"data1":{
"datalist" :[
{ "field1":"value1","field2":"value2"},
{"field1":"value1","field2":"value2"},
{"field1":"value1","field2":"value2"}
]
},
"data2":[ {
"Date":"20 Apr 2016",
"details":[
{"Code":"123","name":"xyz"},
{"Code":"456","name":"abc"}
]
},
{
"Date":"21 Apr 2016",
"details":[
{"Code":"123","name":"xyz"},
{"Code":"456","name":"abc"}
]
},
{
"Date":"22 Apr 2016",
"details":[
{"Code":"123","name":"xyz"},
{"Code":"456","name":"abc"}
]
}
]}
]';
$json_data = json_decode($json);
var_dump($json_data);
Errors in JSON:
You need to double quote your keys:
{
"key": "value"
}
Not:
{
key: "value"
}
After your closing array bracket ] you are adding a ,
should be this:
{
"datalist": [ "blah", "blah"]
}
Not:
{
"datalist": [ "blah", "blah"],
}
The last element in your array should not have a comma after it:
{
"datalist": [{"key1":"value1", {"key2": "value2"}]
}
Not:
{
"datalist": [{"key1":"value1", {"key2": "value2"},]
}

Related

How to get json data to an angular array variable

I am trying to get a json result to an array object .I am echoing a json data in php. like this.
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type:application/json;charset=utf-8');
$arr= '[{
"id": "1",
"date": "2020-03-21",
"status": "present",
"studentid": "1"
},
{
"id": "2",
"date": "2020-03-24",
"status": "present",
"studentid": "1"
},
{
"id": "3",
"date": "2020-03-25",
"status": "absent",
"studentid": "1"
},
{
"id": "4",
"date": "2020-03-26",
"status": "absent",
"studentid": "1"
}
]';
echo $arr;
?>
~
How to get absentees using angular in an array.
Angular part i tried didnt work
this.http.post("http://localhost/android/Api.php?apicall=getattendance", JSON.stringify(this.postData),options)
.subscribe( (data) => {
this.setUsersArray(data);
console.log(data + "URL DATA"+JSON.stringify(this.postData));
}
);
=====================================================================
setUsersArray(data){
if (data instanceof Array) {
{
this.date_present = data.map(function (ele) {
if(ele.status==='present')
{
return ele.date;
}
});
this.date_absent = data.map(function (ele) {
if(ele.status==='absent')
return ele.date;
});
}
}
I am getting date_absent and date_present as null.Why am i getting this as null.Please help me. I am new to angular.
try for loop in typescript
setUsersArray(data:any){
for(let item of data){
console.log(item);
if(item.status==='present') {
this.present.push(item.date);
}
if(item.status==='absent') {
this.absent.push(item.date);
}
}
Trying to this url
$characters = json_decode($data, true); // decode the JSON feed and make an associative array
https://www.taniarascia.com/how-to-use-json-data-with-php-or-javascript/

php parsing multiple json arrays

i have a json file(below) that contains multiple values, it's abit like this -
-makes
- the make
- the model
- year made
- year made
- year made
- the model
- year made
- year made
- the make
- the model
- year made
I can't figure out how to loop through each "make" one by one to get the model and year, Every way iv'e tried so far just seems to produce the make and nothing else.
the output im looking for would look like this(using the snippet below from the full json file)
am general:hummer:1998
am general:hummer:1999
acura:CL:1997
acura:CL:1998
etc..
small snippet of the json file im working with -
{
"makes": [
{
"name": "AM General",
"models": [
{
"name": "Hummer",
"years": [
{
"year": 1998
},
{
"year": 1999
}
]
}
]
},
{
"name": "Acura",
"models": [
{
"name": "CL",
"years": [
{
"year": 1997
},
{
"year": 1998
},
{
"year": 1999
}
]
},
{
"name": "ILX",
"years": [
{
"year": 2013
},
{
"year": 2014
},
{
"year": 2015
}
]
},
{
"name": "ILX Hybrid",
"years": [
{
"year": 2014
}
]
}
]
}
]
}
$data = json_decode($json);
foreach ($data->makes as $make) { // assuming you have gotten this far already...
foreach ($make->models as $model) { // just keep going
foreach ($model->years as $year) { // deeper
echo $make->name . ':' . $model->name . ':' . $year->year . '<br>';
}
}
}
You can open the file using file_get_contents and just decode it :
$file = file_get_contents('path_to_file');
$decoded = json_deconde($file, true); // produces array

How to add element to JSON object using PHP? [duplicate]

This question already has answers here:
how to add item to the json file formatted array
(5 answers)
Closed 7 years ago.
I have this JSON array, and i want to add another value to it using PHP.
What would be the easiest way to add a ID and Name to this array using PHP.
[
{
"id":1,
"name":"Charlie"
},
{
"id":2,
"name":"Brown"
},
{
"id":3,
"name":"Subitem",
"children":[
{
"id":4,
"name":"Alfa"
},
{
"id":5,
"name":"Bravo"
}
]
},
{
"id":8,
"name":"James"
}
]
Simply, decode it using json_decode()
And append array to resulting array.
Again encode it using json_encode()
Complete code:
<?php
$arr = '[
{
"id":1,
"name":"Charlie"
},
{
"id":2,
"name":"Brown"
},
{
"id":3,
"name":"Subitem",
"children":[
{
"id":4,
"name":"Alfa"
},
{
"id":5,
"name":"Bravo"
}
]
},
{
"id":8,
"name":"James"
}
]';
$arr = json_decode($arr, TRUE);
$arr[] = ['id' => '9999', 'name' => 'Name'];
$json = json_encode($arr);
echo '<pre>';
print_r($json);
echo '</pre>';

php How to do a json decode when a child nod is a radom number?

here is a json tree from wikipedia. http://en.wikipedia.org/w/api.php?action=query&titles=japan&prop=categories&format=json
I met a trouble in "pages": { "15573": {. If I will turn the query word, the page number is always changed. How to do a json decode when a child nod is a radom number? Thanks.
{
"query": {
"normalized": [
{
"from": "japan",
"to": "Japan"
}
],
"pages": {
"15573": {
"pageid": 15573,
"ns": 0,
"title": "Japan",
"categories": [
{
"ns": 14,
"title": "Category:All articles containing potentially dated statements"
},
{
"ns": 14,
"title": "Category:Article Feedback Pilot"
},
{
"ns": 14,
"title": "Category:Articles containing Japanese language text"
},
{
"ns": 14,
"title": "Category:Articles containing potentially dated statements from 2010"
},
{
"ns": 14,
"title": "Category:Articles containing potentially dated statements from January 2011"
},
{
"ns": 14,
"title": "Category:Constitutional monarchies"
},
{
"ns": 14,
"title": "Category:Countries bordering the Pacific Ocean"
},
{
"ns": 14,
"title": "Category:Countries bordering the Philippine Sea"
},
{
"ns": 14,
"title": "Category:East Asian countries"
},
{
"ns": 14,
"title": "Category:Empires"
}
]
}
}
},
"query-continue": {
"categories": {
"clcontinue": "15573|Featured articles"
}
}
}
You can do this (based on what you want in comment):
$json_array = json_decode($json, true);
foreach($json_array['query']['pages'] as $page)
{
print_r($page['categories']);
}
I'm assuming you want to access it as array, but you can also do it with the default return value, with little modification of course.
After you decode the json, instead of
$arr["15573"]
access the element with
$arr[0]
Use the index instead of the array key to acces the value.
example:
$array = json_decode( $json_string );
echo $array['query']['pages'][0]['pageid'];
I guess your problem is not decoding but accessing that node, because you don't know the value? That could be obtained via
$decoded = json_decode( $json, true );
$key = array_shift( array_keys( $decoded[ 'query' ][ 'pages' ] ) ) );
Use json_decode($json, true); to transform that string to array
Use array_values to convert keys to indexes starting from 0 :
$pages = array_values($jsondecoded["query"]["pages"]);
Here is the code and output for you: http://codepad.org/3Usm47YZ

PHP JSON Data Selection

How would I go about selecting the data of each title from the following JSON?
I have the JSON decoded, but I'm not sure how to select the part I want.
{
"responseData": {
"results": [
{
"title": "Justin Giesbrecht 749",
"titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
I thought it would be something like this, but I don't get anything:
echo "Response ". $jsonS->responseData->results[1]->title;
Actually you've got the reading of the title part right, it's the JSON that is invalid.
Copying the JSON into a JSON validator/lint e.g. http://www.jsonlint.com/ will show that the you have additional , (commas) after the last object attribute in a few places (5 places to be exact, after each 'titleFormatting' attribute and after 'currentPageIndex').
If you fix those errors and parse it using json_decode e.g.:
$jsonS = json_decode($json_text);
Then your own code:
echo "Response " . $jsonS->responseData->results[1]->title;
Will output the second (index 1 being the second index) results title
Response Gopher dunes 09
When you json_decode something it is converted to a regular PHP array, so you can reference it like $decodedObject["nodeName"].
When I parse that JSON as you quoted it with PHP's json_decode method, it gives me NULL because PHP doesn't think it's valid JSON. Add a var_dump($jsonS); to see if this is happening to you as well. If it is, you may need to be sure your JSON is valid.
Here's what I did, for reference:
$json_data = <<<END_OF_JSON
{
"responseData": { "results": [
{
"title": "Justin Giesbrecht 749", "titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [ {
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
END_OF_JSON;
$jsonS = json_decode($json_data);
var_dump($jsonS);
echo "Response ". $jsonS->responseData->results[1]->title;
And the output was:
NULL Response
If you're using different JSON, please edit your question and share it. But if you're actually using the above, it's not valid...
In JSON you are not allowed to leave trailing comma in array/object definition. So, when in PHP is perfectly valid to write:
$a = array(1,2,3,);
(note last comma), in JSON
a : [1,2,3,]
or
a : {x :'y',}
is invalid.

Categories