I have the following json output - I've tried multiple things however not having any luck - I just want to get the value for kind (software-package). Any ideas:
{"items":
[{"assets":
[{"kind":"software-package","url":"__URL__"}],
"metadata":{"bundle-identifier":"SimpleCalculator",
"bundle-version":"000","kind":"software",
"title":"com.work.demo","subtitle":"1.0"}
Thanks,
Try to decode it with json_encode like
$result_arr = json_decode($my_arr,true);
print_r($result_arr['items']['assets']['kind']);
That is not valid JSON.
Lets attempts to format that a little more sensibly.
{"items": [
{"assets": [
{"kind":"software-package","url":"__URL__"}
],
"metadata":{"bundle-identifier":"SimpleCalculator",
"bundle-version":"000","kind":"software",
"title":"com.work.demo","subtitle":"1.0"
}
You're missing a lot of closing brackets. :(
How are you acquiring this JSON. Is it hand formatted or generated by some software? They're may be bugs in the source, and not your code.
If you are using a version of PHP above 5.3 then there are built-in functions to decode and encode JSON strings already.
$some_json_string = {......};
$json_string_as_object = json_decode($some_json_string);
$json_string_as_array = json_decode($some_json_string, true);
You can also do the reverse:
$some_array = array(...);
$json_string = json_encode($some_array);
Json Decode : http://php.net/manual/en/function.json-decode.php
Json Encode: http://www.php.net/manual/en/function.json-encode.php
Related
For example i have json strings like this ( from the first place ). And It's not formatted.
{"data":[{"id":"14","memo_kondisi":"Kekurangan
pekerjaan","total_row":"5","nilai_temuan":"1.000.000","data_sebab":[{"id":"15","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"25","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"26","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"31","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]},{"id":"16","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"34","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"35","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]}]},{"id":"15","memo_kondisi":"Kekurangan
pekerjaan","total_row":"2","nilai_temuan":"1.000.000","data_sebab":[{"id":"5","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]},{"id":"10","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]},{"id":"16","memo_kondisi":"","total_row":"2","nilai_temuan":"0","data_sebab":[{"id":"9","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]},{"id":"12","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]}]}
I see some similar question that you have to use json_decode and i have to encode again and using json_encode($json,JSON_PRETTY_PRINT)
Is there a way for make json readable without decode the JSON first and encode it again in PHP ?
Note : I expect the result is still in JSON
Not really. Using someone else's parser lib won't make any difference, as they'll call json_decode() too.
You could create a little function that you could call:
function prettify($json)
{
$array = json_decode($json, true);
$json = json_encode($array, JSON_PRETTY_PRINT);
return $json;
}
Then echo prettify($jsonString); would be easier than constantly decoding and re-encoding. See here https://3v4l.org/CcJlf
Only a parser can understand the JSON, so you can either do what you proposed or write your own parser. If you have access to the origin of the JSON, make it pretty in the first place.
I am trying to decode json with PHP but dont know where am i wrong. Here is my code
$rr ='var modelsGlobal = [{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}]';
$json = json_decode($rr, true);
foreach($json['modelsGlobal'] as $json){
$prod_id = $json["value"];
}
Please help
You are trying to decode (broken) JavaScript, not JSON.
JSON wouldn't include var modelsGlobal = and array members need a , between them.
Run your data through a linter.
After you fix the errors which are preventing the parsing, the JSON doesn't start with an object with a modelsGlobal, so loop over the array in $json directly.
Your JSON is incorrect. It is not JSON but JavaScript and it lacks a comma to separate the two objects of the array.
If you use PHP 5.3+ use json_last_error to check errors with json_encode/json_decode.
Here's the info I'm trying to break up into a database. I'm going to be using this only for my own use to analyse statistics and all that. I have been manually doing it with Excel but I'd like to save myself some work in future.
URL IS: http://fantasy.premierleague.com/web/api/elements/537/
Any idea how to scrape that info or easily convert it to excel format? I know a bit of php and mysql, but nothing about JSON and very little about scraping (I tried messing with SIMPLE_HTML_DOM).
You need to JSON_decode the data in PHP.
$obj = JSON_decode($mydata));
print_r($obj);
Extra information for you:
http://php.net/manual/en/function.json-decode.php
You can convert it into an array as
$array = json_decode(file_get_contents('http://fantasy.premierleague.com/web/api/elements/537/'));
json_decode()
You could use PEAR excel writer to convert it into excel
PHP has a json parser function json_decode().
So:
Use the file_get_contents() function to read the json content from the URL into a string.
Use json_decode() to create a PHP structure representation.
Use PEAR Spreadsheet_Excel_Writer module to create your excel spreadsheet.
Yeah. Easy as 1, 2, 3.
<?php
$x=json_decode(file_get_contents('http://fantasy.premierleague.com/web/api/elements/537/'));
print_r($x);//$x will contain all the values in an array format.
?>
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$json= file_get_contents('http://fantasy.premierleague.com/web/api/elements/537/', false, $context);
$arr= json_decode($json);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($arr, array ($xml, 'addChild'));
print $xml->asXML();
PHP makes it very easy:
$str = file_get_contents('http://fantasy.premierleague.com/web/api/elements/537/');
$jsonarray = json_decode($str, true);
var_dump($jsonarray);
Of course you will have to analyze the structure of the array and figure out how to decompose it to what you are actually looking for.
Try using $obj = json_decode($jsonStr) after you receive your response string by running curl on the URL you mentioned in PHP. Then you can grab params from the json object like
$obj['paramName'];
Then you can do anything you want with the information including putting it into a database.
For simple MySQL interaction in php, check out MySQLConnector class.
http://jakesankey.com/blog/2011/12/php-mysql-helper-class/
use just json_decode and get the converted data like this edit
$arr = json_decode('your JSON data',true);
echo $arr['transfers_out']; // output 490374 //for array
echo $arr->transfers_out; // output 490374 //for stdClass
I am preparing and sending a JSON string from my PHP file to my Javascript function like this:
$json = array();
$json['slice'] = false;
$json['G500'] = false;
$json['KG1'] = false;
$encoded = json_encode($json);
die($encoded);
However, in my JS function, if I do this, it is unable to decode the JSON object:
var d = req.responseText;
var jsonObject = eval(d);
The only way, I can get it to eval the JSON object is by adding parentheses manually
jsonObject = eval("(" + d + ")");
I have the same problem going in reverse as well. Sending a JSON object to PHP and trying to decode it there fails. I believe I would need to remove the parentheses in my PHP script before attempting to decode.
Why is this happening? Is there something I can do to work around this incompatibility?
EDIT:
PHP to JS is now working if I use JSON.parse. I'm still having trouble the other way around.
This is how I'm sending the data to the PHP:
var JSONstring =
{
"Product": document.getElementById('item').value,
"Size": document.getElementById('size').value,
"Quantity": document.getElementById('quantity').value
};
url = "maintainOrder.php?json=" + JSON.stringify(JSONstring);
req.open("GET", url, true);
However, the PHP script is unable to decode it.
$newItem = json_decode($_GET['json']);
array_push($_SESSION['order'],$newItem);
Your Javascript
eval has an issue with leading { characters, because of an ambiguity with block scope.
Using the parentheses to force the input to be parsed as an expression is a solution, but you should avoid eval entirely and use a proper JSON decoding function.
Your PHP
We'd need to see the data that you send to your PHP script to know why it won't parse. In general, as long as JSONLint accepts your JSON, so will PHP's json_decode. So give that a go.
For the php to javascript issue refer to the Tomalak Geret'kal answer.
For the javascript to php maybe I have the solution:
If you want an associative array in php then you have to pass assoc parameter as true into json_decode (default to false)
Example:
$array = json_decode($jsonString, true);
I was bitten a couple of times by this: by default json_decode try to create an object if it receive a javascript object (it make perfect sense if you think of) and you have to force it to render an associative array if you need this behaviour
I think you need to do some string processing, all you need to do is echo and see the exact format of your JSON string and make sure it conforms to the standard format, then use string processing both on the server and client sides to achieve the desired effect
Are you sure php is not adding slashes to the json text?, try saving the json text in a file in the server side to verify
I am running a Debian box with PHP v5.2.17. I am trying to get around the cross-domain issue with an XML file and am using this got to fetch any xml and return json:
<?php
header('content-type: application/json; charset=utf-8');
if( strlen($_GET["feed"]) >= 13 ) {
$xml = file_get_contents(urldecode($_GET["feed"]));
if($xml) {
$data = #simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($data);
echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
}
}
?>
The problem is, its not returning valid json to jquery.. The start character is "(" and the end is ")" where jquery wants "[" as the start and "]" as the end. I've taken the output and used several online validation tools to check it..
Is there a way I can change these characters prior to sending back or pass json_encode options?
You could change json_encode($data) to json_encode(array($data)) if it expects an array (like you're saying):
$json = json_encode(array($data));
EDIT: Also, I believe the SimpleXml call will result in a bunch of SimpleXmlElements, perhaps json_encode then thinks it should be objects, instead of arrays? Perhaps casting to an array will yield the correct results.
You cannot json_encode() SimpleXMLElements (that's the type that is returned by simplexml_load_string(). You have to convert the data from the XML file into some native PHP type (most likely an array).
SORRY that's wrong. json_encode() can in fact encode SimpleXMLElements (at least on my PHP version 5.3.4). So if your client-side code expects an array you must wrap your $data in an array:
$json = json_encode(array($data));
We can use json_encode() function most probably on array. so you first take XML content into PHP array and then apply json_encode().I think this will solve your problem..
It seems that you are sending an empty callback parameter or something, but the callback parameter in jQuery must look exactly like this: callback=?