I want to extract a specific data from a json string [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 7 months ago.
This is my code , how can I achieve it plz help
<?php
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [{"data":
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
}]
}';
$yummy = json_decode($json);
echo $yummy->toppings[0]->data[2]->id;

Fix the JSON, you're missing brackets. Once you fix this your code will work (it returns 5004 in your example)
{
"type": "donut",
"name": "Cake",
"toppings": [{"data":
[{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }]
}]
}
There are online tools that help you find these little issues.
https://jsonformatter.curiousconcept.com/

Related

Converting JSON from URL to CSV with PHP

When I run the code below it results in the first row in a long list of columns containing only the text Array.
I've used $decoded = json_decode($json_file, true); to indicate that I want arrays instead of objects so I'm not sure what the issue is.
Should I be using bracket or arrow notation somewhere to specify that I want the array values?
$json_file = file_get_contents('https://fakeurl.com&contentType=json', false);
$decoded = json_decode($json_file, true);
$fp = fopen('output.csv', 'w');
foreach($decoded as $comment) {
fputcsv($fp, $comment);
}
fclose($fp);
Here is a small snippet of the JSON. It looks like this all the way through:
{
"rows": [{
"columns": [{
"name": "clientId",
"value": "1839",
"type": "xs:int",
"format": ""
}, {
"name": "campaignId",
"value": "25646",
"type": "xs:int",
"format": ""
}, {
"name": "campaignStatus",
"value": "Live",
"type": "xs:string",
"format": ""
}, {
"name": "campaignName",
"value": "Template Donation Litle",
"type": "xs:string",
"format": ""
}, {
"name": "campaignExportName",
"value": "Template Donation Litle",
"type": "xs:string",
"format": ""
}, {
"name": "description",
"value": "/donate/template/Litle",
"type": "xs:string",
"format": ""
}]
}, {
"columns": [{
"name": "clientId",
"value": "1839",
"type": "xs:int",
"format": ""
}, {
"name": "campaignId",
"value": "25812",
"type": "xs:int",
"format": ""
}, {
"name": "campaignStatus",
"value": "Live",
"type": "xs:string",
"format": ""
}, {
"name": "campaignName",
"value": "Monthly Only",
"type": "xs:string",
"format": ""
}, {
"name": "campaignExportName",
"value": "Monthly Only",
"type": "xs:string",
"format": ""
}, {
"name": "description",
"value": "A donation receipt will be emailed to the address you submitted. This donation is tax-deductible to the fullest extent of the law.",
"type": "xs:string",
"format": ""
}]
}]
}
Your array is much deeper and the values need to be extracted:
foreach($decoded['rows'] as $row) {
$values = array_column($row['columns'], 'value');
fputcsv($fp, $values);
}
If you want the names/headers in the first row then you need to do this before the loop:
$headers = array_column($decoded['rows'][0]['columns'], 'name');
fputcsv($fp, $headers);

Json Schema - Validate an infinite recursive structure

I'm trying to validate a json object using the "justinrainbow/json-schema" package for php.
Here's the json that i'm trying to validate:
{
"questions": [
{
"type": "section",
"name": "Section one",
"questions": [
{
"type": "section",
"name": "Subsection 1.1"
"questions":[
{
"type": "section",
"name": "Subsection 1.1"
"questions":
[
{
...
}
]
}
]
}
]
}
]
The questions property can always be present inside questions property ....
How can i validate it?
Thank you for your answers
You can use $ref to define a recursive structure.
{
"type": "object",
"properties": {
"type": { "type": "string" },
"name": { "type": "string" },
"questions": { "type": "array", "items": { "$ref": "#"} }
}
}

I want this json to be displayed in angular

I want this multilevel array of jason in angular format i am not being able to do it.
Json file to be displayed in angular goes here.
I am able to display properties and geometry not others
{
"type": "FeatureCollection", //first fie
"metadata": {
"generated": 1456209730000,
"api": "1.4.0",
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 2.3,
},
"geometry": {
"type": "Point",
"coordinates": [
-150.7703,
63.5849
]},
"id": "ak12869032"
},
{
"type": "Feature",
"properties": {
"mag": 2.43
},
"geometry": {
"type": "Point",
"coordinates": [
-120.8253326,
36.6078339
]},
"id": "nc72596150"
}],
"bbox": [ //last field
-150.7703,
33.7698333
]}
Please follow these steps:
1) create $scope.tempData variable in your controller
2) get your value in $scope
3) $scope.tempData=[your json data];
4) you can use tempData in anywhere within controller.
for(var d in tempData)
{
var data=tempData[d].id;
}
now you are able to getting id from your json.but for its giving last value.
so you can cretae array and pushed on every loop.
5) if you want use in html can use ng-repeat.
If you are beginner vist my blog.
Edit your json:
{
"type": "FeatureCollection",
"metadata": {
"generated": 1456209730000,
"api": "1.4.0",
"count": 3
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 2.3,
"place": "93km WNW of Cantwell, Alaska",
"time": 1456207082000
},
"geometry": {
"type": "Point",
"coordinates": [
-150.7703,
63.5849
]
},
"id": "ak12869032"
},
{
"type": "Feature",
"properties": {
"mag": 2.43,
"place": "42km WSW of Mendota, California",
"time": 1456206494170
},
"geometry": {
"type": "Point",
"coordinates": [
-120.8253326,
36.6078339
]
},
"id": "nc72596150"
}
],
"bbox": [
-150.7703,
33.7698333,
0.79,
-115.9471667,
63.5849,
8.8
]
}
See the points: http://bl.ocks.org/d/60bc280edef4ed4da464
To display json in angularjs, please use filter json with model.
<input type="text" ng-model="(jsonData | json)">{{jsonData | json}}</input>
Using Pre Tag we can style it in html page
In your Controller:
$scope.details={name:"xyz",address:[{place:"cc"},{place:"second"}]}
In HTML Page: <pre>{{details|json}}</pre>

Retrieving likes of Facebook Posts in php

I am looking for a way to retrieve the number of likes of a Facebook post, based on its post_id. I got hold of a php code from this forum itself..and it's something like
<?php
function fetchUrl($url){
return file_get_contents($url);
}
$json_object = fetchUrl("https://graph.facebook.com/{post_id}/likes?access_token={token}&limit=5000000"); //
$feedarray = json_decode($json_object, true);
$likesNum = count($feedarray['data']); // return the number of items in `data` array
print $likesNum;
?>
But the problem is this method does not retrieve the total likes of a post, since likes are displayed in blocks of 1000, after which theres another link to a different page containing the next set of 1000 likes and so on.
Is there a way to get the total number of likes of a facebook post by a single query?
Add the summary flag ** summary=true**
"https://graph.facebook.com/{post_id}/likes?access_token={token}&summary=true"
{
"data": [
{
"id": "663342380429664",
"name": "Luis Mendoza"
},
{
"id": "1532100840406448",
"name": "Sakazuki Akainu"
},
{
"id": "780666205412913",
"name": "Joaito KoRn"
},
{
"id": "1060933433919925",
"name": "Adrian Sosa"
},
{
"id": "860704407276452",
"name": "Sarah Rosenstrauch"
},
{
"id": "1947974762009431",
"name": "David Prieto"
},
{
"id": "804864302928112",
"name": "Ronal Ortega"
},
{
"id": "1505075359814934",
"name": "Gonzalo Larzen"
},
{
"id": "1431207613804483",
"name": "Victor Clc"
},
{
"id": "508785009283633",
"name": "Rxdry EzDe Cerrx Mcmxii"
},
{
"id": "435355413265946",
"name": "Ángel Fernando Huillca Alonso"
},
{
"id": "163773913961445",
"name": "Pelado Miguel Pin Macias"
},
{
"id": "1479227465674392",
"name": "Releck Solitario"
},
{
"id": "161610054193539",
"name": "MD Sahin MD Sahin"
},
{
"id": "798431050242097",
"name": "Brian Nahuel"
},
{
"id": "624869574305480",
"name": "Saul Alfredo"
},
{
"id": "1642733362665392",
"name": "Junior Zurita"
},
{
"id": "134907406871404",
"name": "Wil Peña"
},
{
"id": "10153052770952668",
"name": "Miguel Peña Cáceres"
},
{
"id": "1461494580846182",
"name": "Darian Suarez"
},
{
"id": "365762500250317",
"name": "Igarashi Ganta"
},
{
"id": "750032685093387",
"name": "Camila Barbé"
},
{
"id": "781013541941152",
"name": "Gonzalo Nievas"
},
{
"id": "756520927743339",
"name": "Jonathan C. Duran Cuellar"
},
{
"id": "1504488093199860",
"name": "Maxi Russo"
}
],
"paging": {
"cursors": {
"before": "NjYzMzQyMzgwNDI5NjY0",
"after": "MTUwNDQ4ODA5MzE5OTg2MAZDZD"
},
"next": "https://graph.facebook.com/v2.3/1009501939072385/likes?access_token=TOKEN..."
},
"summary": {
"total_count": 4303
}
}

Verify one layer only

I want to verify a variable holding json only has one level simple format. Can someone provide an example where only one level is verified - not a multi-level verification?
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
isValidOnlayer($json); // True
$json = '{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}'
isValidOnlayer($json); // False
?>
You can use this as a result of your function:
count(array_filter(json_decode($json, 1), 'is_array'))
$tmp = json_decode($json, true, 2); // depth=2, the array "itself" is level 1, its elements are level 2
if $tmp is null an error occurred. In case the depth limit was the problem json_last_error() will return JSON_ERROR_DEPTH

Categories