How parse JSON from file? - php

I have json file with this this code:
{
"data": [
{
"id": 33940157205526204,
"user": {
"id": 548844917,
"full_name": "DelacruzHayden",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/87947328356424110_1657580247886246_102415570_a.jpg",
"username": "Noreen Lang"
},
...
]
}
When I want to parse it:
$data = file_get_contents("/home/lumawu/test.json");
do {
$medias = json_decode(json_encode($data),true);
foreach ($medias['data'] as $media) {
I get the error:
[ErrorException]
Illegal string offset 'data'
How to decode it?

In your code you just need to do json_decode($data, true) to get the json string to an array.
If you do both json_decode(json_encode($data, true)),
the json_encode will encode the json string and the next json_decode will not be able to decode json correctly.
So your code should be something like this:
$data = file_get_contents("/home/lumawu/test.json");
do {
$medias = json_decode($data,true);
foreach ($medias['data'] as $media) {

Related

Extract each level data with php

The following is the JSon data.
{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}
I need to parse
- entity
- quizAnswerChoices (count the item)
How to retrieve each choiceText etc
Use
$json='{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}';
$encodedJson= json_decode($json,true);
$quizAnswerChoices=$encodedJson['entity'][0]['quizAnswerChoices'];
echo 'Count: '.count($quizAnswerChoices);
Use this
$arry = json_decode($json,true);
foreach ($arry['entity'] as $ke => $ve) {
foreach ($ve['quizAnswerChoices'] as $k => $v) {
print_r($v);
}
}
Lets consider you are recieving this json in a variable called "$contents".
All you have to do is decode it:
$decoded = json_decode($contents, true); //True so, the decoded object will be converted into an ssociative array
print_r($decoded);
If you do a json_decode like
$data = json_decode(json_data);
Then $data will be a traversable array
$data['entity']['quizAnswerChoices'] etc
Use json_decode to convert json to array
$dataArray = json_decode($json_string, true)
$dataArray['entity']; // entity
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
count($dataArray['entity']['quizAnswerChoices']); // quizAnswerChoices count

how to convert this malformed string to json with php/jquery

I have this string -
{
'Carlos':
{
Name: 'Spers',
href: "http://google.com"
},
'Winter':
{
Name: 'Warres',
href: "http://yahoo.com"
},
'Doer':
{
Name: 'Pinto',
href: "http://carpet.com"
}
}
I validated the with JSLinter, it say invalid with multiple errors. And I understand that. The issue is, this is what I get from a third party service. I have to leave with it. Now I'm stuck with it to convert into JSON object to work with it.
When I use json_decode($thisStirng) in PHP, it returns null. $.parseJSON(data) returns me errors too.
I would like to show the data on the webpage with some styling. So at the end, I want json object at the client to work with. So converting data to JSON with PHP or jQuery, anyway would work.
How should I go about it?
Update
I got an associative array with json_decode($thisStirng, true). Now I want echo it as a string so that on browser, I could access it with array indexes.
Thank you all - got it working as below -
$someObject = json_decode($thisStirng,true);
$myarry = array();
foreach ($someObject as $key => $val) {
$temparray = array();
$temparray[]= $key;
$temparray[]= $val;
$myarry[]= $temparray;
}
echo json_encode($myarry);
Now in jQuery I can access, data[index][0] as 'Carlos' and other dynamic keys. data[index][1] is an object with 'Name' and 'href' properies.
You can try this code.
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$arr1=array();
$arr2=array();
$arr3=array();
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
$arr1=array();
$arr1[]=$key;
foreach ($value as $k => $v) {
$arr2=array();
$arr2[$k]=$v;
$arr3[]=$arr2;
}
}
echo $arr3[0]['Name'];
try using this:
<?php
$jsonData='{
"Carlos":
{
"Name": "Spers",
"href": "http://google.com"
},
"Winter":
{
"Name": "Warres",
"href": "http://yahoo.com"
},
"Doer":
{
"Name": "Pinto",
"href": "http://carpet.com"
}
}';
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) {
echo "Key:".$key. ", Name:". $value['Name'].'<br>';
}
?>
OUTPUT:
Key:Carlos, Name:Spers
Key:Winter, Name:Warres
Key:Doer, Name:Pinto

Delete from JSON with PHP

I'm trying to delete an item from a JSON file using the id of the item.
This is the code I'm using to do so.
if($id){
header('Content-Type: application/json');
$id = $_GET['id'];
$file = file_get_contents("data.json");
$json = json_decode($file);
foreach ($json->items as $item) {
if ($item->id == $id) {
unset($item);
file_put_contents('data.json', json_encode($json));
header('HTTP/1.1 204 No Content');
}
}
}
The RESTclient I'm using gives the 204 but when I look in my JSON file, the item is still there.
Any idea what I'm doing wrong?
EDIT
JSON looks like this
{
"items": [
{
"id": 1,
"title": "title",
"artist": "artist",
"genre": "genre",
"links": [
{
"rel": "self",
"href": "link/webservice/music/1"
},
{
"rel": "collection",
"href": "link/webservice/"
}
]
},
Inside a foreach-loop the copy of the array element you've got does not affect the original array in some ways.
You need to dereference the array item using the original array or pass it to the loop by reference.
The following should work, I guess:
if($id){
header('Content-Type: application/json');
$id = $_GET['id'];
$file = file_get_contents("data.json");
$json = json_decode($file);
foreach ($json->items as $key => $item) {
if ($item->id == $id) {
unset($json->items[$key]);
file_put_contents('data.json', json_encode($json));
header('HTTP/1.1 204 No Content');
}
}
}

PHP: How to get a value from a JSON file?

I'm using PHP and json_decode to use a remote API and I'm having what seems to be a newbie problem for which I didn't even know what to search to find my answer.
So on my script I have a $code = 392 and a json file which simplified version is:
{
"result": {
"items": [
{
"name": "New York",
"code": 7294,
},
{
"name": "Miami",
"code": 392,
},
{
"name": "Los Angeles",
"code": 9182,
}
]
}
}
So, simply put, having the code 392 I want to know which name corresponds to that code. How ?
(The actual json result has thousands of "items", if that makes a difference)
At first you should decode your json data like:
// will decode json data as assoc array
$data = json_decode($json_data, true);
Then, you can get value in this array like:
$item01 = $data['result']['items'][0];
$name = $item01['name']; // New York
$code = $item01['code']; // 7294
Or
// will decode json data as object
$data = json_decode($json_data);
$item01 = $data->result->items[0];
$name = $item01->name; // New York
$code = $item01->code; // 7294
You can iterate through items in result of your JSON object, and check for equality with the desired code, and each item's code. Here's how you would implement it into a function.
function getNameFromCode($json, $code) {
foreach ($json['result']['items'] as $item)
if ($item['code'] == $code)
return $item['name'];
// return false if the code wasn't found.
return false;
}
// assume this is the JSON string of your example.
$json_string = "...";
// pass true as the second argument to get an associative array.
$json = json_decode($json_string, true);
// should return "Los Angeles".
$name = getNameFromCode($json, 9182);
Documenation on foreach().
foreach( json_decode($my_json_string) as $key => $item)
if ( $item['code'] === $code ) { $name = $item[name]; break; }
You can convert JSON to PHP object and loop through the items with foreach loop.
function getNameByCode($phpobj, $code){
if( isset($phpobj->result) ){
if( isset($phpobj->result->items)
&& is_array($phpobj->result->items) ){
foreach($phpobj->result->items as $item){
if( $item->code == $code ){
return $item->name;
}
}
}
}
return false;
}//end function
You can test with this ... NOTE: trailing commas are removed as suggest by rjdown in comment
$json = '{
"result": {
"items": [
{
"name": "New York",
"code": 7294
},
{
"name": "Miami",
"code": 392
},
{
"name": "Los Angeles",
"code": 9182
}
]
}
}';
$phpobj = json_decode($json);
$name = getNameByCode($phpobj, "7294");
echo $name;

read json like facebook json php

i try to read json by php
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}}
i try by this code
$sfgsdfg= $json_a=json_decode($read,true);
echo $json_a['data'][3043252fsdgdf36360354];
echo $json_a['3043252fsdgdf36360354'][access_token];
not working with this php code i need help to read it
i need select access_token by 3043252fsdgdf36360354 as echo $json_a['data'][3043252fsdgdf36360354]['access_token'];
i need only read by id as . mysql command . select access_token where id ='3326848fdgsdfgsdf03424168';
First of all, your JSON is missing a ] character and will cause json_decode to return NULL. You should first correct the JSON string. You can use a online service such as jsonlint.com to validate the JSON. Once you've decoded the JSON string as an associative array, you can just loop through the array and check if it contains the given ID in it. If it does, you can grab the corresponding access token easily.
I've made this into a short little function. You can use that to get the access token by ID:
$jsonArray = json_decode($str, TRUE);
function getAccessTokenFromID($id, $jsonArray) {
foreach ($jsonArray['data'] as $k => $elem) {
if($elem['id'] == $id) {
$access_token = $elem['access_token'];
}
}
return $access_token;
}
Usage:
$myid = '3043252fsdgdf36360354';
$my_accesstoken = getAccessTokenFromID($myid, $jsonArray);
Demo!
Isn't well formed json.
Try with:
{
"data": [
{
"id": "3043252fsdgdf36360354",
"name": "name1",
"access_token": "CAAIf3VEtVSoBAHrVxHL16zt4H5OvwBmdfgs4F3auPE0NZBx5PmIujBAdqw0Cv4bZACXytT1O1y6FHEZA25E1aqQZD"
},
{
"id": "3326848fdgsdfgsdf03424168",
"name": "name2",
"access_token": "CAAIf3VEtVSoBAJinePVdfgsdfgMxuY3zaj9AimaoKx7VIO9jCqZCHC6ZBixL1n6ZC72LTMn0ZB4T8rOHD27WmzbBVgvUwgspeEZD"
}
]
}
And php:
$val = json_decode($read, TRUE);
echo $val['data'][0]['id'];
UPDATED:
function find_by_id($id, $val) {
foreach($val['data'] as $key => $obj) {
if ($obj['id'] === $id)
return $obj['access_token'];
}
}

Categories