json_encode, json_decode, array? - php

I'm trying to get into just data from
{
"data": [{
"media_count": 3045,
"name": "snow",
},
{
"media_count": 79,
"name": "snowman",
},
{
"media_count": 40,
"name": "snowday",
},
{
"media_count": 29,
"name": "snowy",
}]
}
I've been trying, using:
$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array
I also tried this:
$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`
"data": [{
"media_count":54373,
"name":"test"
}]
I just want to get inside data. How would I do so?
Thanks in advance!
UPDATE: Sorry to mention, I would like this in json format please
eventually, I would like to only see
{
"media_count":54373,
"name":"test"
}
Something like thiat

Use json_encode() to get what you want:
$obj = json_decode($res[0], true);
echo json_encode($obj['data']);

In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.
To access within the array, you can do this:
foreach($obj['data'] as $object) {
print_r($object);
}
You can also index into it as you want:
print_r($obj['data'][0]);
EDIT
If I'm getting you correct, you want to convert the first JSON to this:
"data": [{
"media_count":54373,
"name":"test"
}]
If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)

firstly access the data item of the json array;
$obj1=$obj[item];
$sizeobj=sizeof($obj1);
for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}

Related

JSON Parsing Error: Warning: Attempt to read property on array

am trying to parse this JSON from a Football API using PHP.
Below is a subset of the JSON output.
Specifically, I am trying to retrieve the “45%” value from the "home" element from the below json.
$json = '{
"get": "predictions",
"parameters": {
"fixture": "198772"
},
"errors": [],
"results": 1,
"paging": {
"current": 1,
"total": 1
},
"response": [{
"predictions": {
"winner": {
"id": 1189,
"name": "Deportivo Santani",
"comment": "Win or draw"
},
"win_or_draw": true,
"under_over": "-3.5",
"goals": {
"home": "-2.5",
"away": "-1.5"
},
"advice": "Combo Double chance : Deportivo Santani or draw and -3.5 goals",
"percent": {
"home": "45%",
"draw": "45%",
"away": "10%"
}
}
}]
}';
I have tried the following codes but it does not work
$response = json_decode($json);
echo 'Output: '. $response->response->predictions->percent->home;
The error i am getting is:
Warning: Attempt to read property "predictions" on array in C:\xampp\htdocs\xampp\livescore\api-test\predictions.php on line 93
I also tried this but no luck.
echo 'Output: '. $response->response[0]->predictions[0]->percent[0]->home;
appreciate any help or insights I can get.
thanks in advance.
Whenever you see a [ in a json (or any other) object, it's the start of an array, and to reach a child of that array you have to reference it's index (postition). For what you want, this would do it.
$response = json_decode($json);
echo 'Output: '. $response->response[0]->predictions->percent->home;
"response": [{ shows the beginning of an array, and since there's only one item in the array (starting with {) you can reference it by it's index 0. If there were many items in the array, you could loop over them, like
$response->response.forEach(arrayItem => {
// arrayItem is the current element in the array you're looping though
})
You've probably missed that only value of "response" is an array, which has dictionary inside.
Try this: $response->response[0]->predictions->percent->home

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.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data

when i use....
var jsonData = JSON.parse(xhttp.responseText);
i get an error => "JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data"
this is my JSON data from a php script
{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}
Can some please help?.... Thanks
A little bit late to the party, but #igniz87 and #Benjamin James Kippax's answers open your website to security issues, and it is so dangerous to follow their example.
As Owasp reads,
ALWAYS RETURN JSON WITH AN OBJECT ON THE OUTSIDE
Hence, so as to be a layer protected from the barbarism of hackers, you need to ALWAYS have the outside primitive be an object for JSON strings. As you can clearly see, the mentioned people's answers do not follow this crucial security rule.
Owasp, moreover, brings an example and says that a JSON like the following is EXPLOITABLE:
[{"object": "inside an array"}]
Yet, the following JSONs are not,
{"object": "not inside an array"}
{"result": [{"object": "inside an array"}]}
You need to remove the duplicate key element and change it in the following way so you will have an object on the outside.
{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}],
"resultss": [{
"oldID": 3,
"oldMain": "Construction"
}]}
Here, actually you should have brought you php code, as the problem is with that php code which is sending the JSON. When you want to send the JSON try to make an array of your data. I do the following way.
$data = [];
foreach ($results as $res) {
$t = [];
$t['oldID'] = $res['oldID'];
$t['oldMain'] = $res['oldMain'];
$data[] = $t;
}
echo json_encode(['results' => $data]);
You'd better send your php code which is lacking here. My php script does not contain all of your code, but it gives you idea how to do it.
I have had the same problem for the past several years.
Sometimes the problem is not related to invalid JSON .. like me now.. the problem is that I must use stringify before JSON.parse
var db = JSON.stringify(data);
var db = JSON.parse(db);
And sometimes in php you must use json_encode($data) correctly.
And sometimes your JSON is not valid ( Online JSON Validator )
The JSON is not valid. If it is possible, you can update the JSON as following
{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}],
"resultss": [{
"oldID": 3,
"oldMain": "Construction"
}]}
And also JSON should not contain duplicate key elements. Also you can club the JSON to JSONArray like this
[{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}]
},
{
"results": [{
"oldID": 3,
"oldMain": "Construction"
}]
}]
it's not a valid json, you must wrap it in array. the valid json is like this
[{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}]
}, {
"results": [{
"oldID": 3,
"oldMain": "Construction"
}]
}, {
"results": [{
"oldID": 2,
"oldMain": "Banking Files"
}]
}, {
"results": [{
"oldID": 1,
"oldMain": "Technologies"
}]
}]
take a look at the bracket [ ] at the start and the end of string , and the , to split the object.
this some online json linter here to check if your json is valid.
Your code is invalid.
Your code;
{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}
Your code validated;
[{"results":[{"oldID":5,"oldMain":"News papers"}]},
{"results":[{"oldID":3,"oldMain":"Construction"}]},
{"results":[{"oldID":2,"oldMain":"Banking Files"}]},
{"results":[{"oldID":1,"oldMain":"Technologies"}]}]
The problem is that you had multiple JSON root elements. These also weren't comma separated. They also need wrapping in [], which will turn it into an object. If you don't want to wrap your response in [], you can return the string without the [] and instead do this;
JSON.parse('['+yourreponse+']') which will parse the JSON correctly.
Above answer are correct i.e. your json syntax is incorrect. Correcting your syntax would solved the problem (as suggested)
My case was a little different. I was returning json in response to ajax calls. Those jsons where returned by php using a if else construct. Where I mistakenly omitted one else;
if (!empty($_GET['arg1']))
echo getTrainings($filter, 'arg1');
elseif (!empty($_GET['arg2']))
echo getTrainings($filter, 'arg2');
if (empty($_GET['arg3']))
echo getTrainings($filter, 'arg3');
elseif (empty($_GET['arg4']))
echo getTrainings($filter, 'arg4');
So in fact two json where being returned instead of one, that caused problem for $.parseJSON(result);
var par = $.parseJSON(result);

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

Categories