how to get values of an array that is inside an object? - php

i've got an object that contains two elements, the first is a string, the second one is an array, i need to return only the array.
here is the object :
{
"return_code": 0,
"response": [
{
"tid": "30",
"categorie": "Fish"
},
{
"tid": "31",
"categorie": "Birds"
}
]
}
I want to return the "response". Any help please ?
Thank you.

Here's the basic idea based on new comments:
Decode the JSON string you're getting using json_decode in PHP. This will give you a PHP object.
Create an empty list to contain the elements you want in the result.
For each element in the response property of the decoded JSON object, add response.categorie to your list container.
Return the now full list

Your data looks like JSON, so I will propose a solution in jq ("Json Query") - a language that is readily available on most modern computing platforms -- see https://stedolan.github.io/jq/
The originally posted task was to find the array. In jq, this can be accomplished using the program: .response
Subsequently, the task was revised to extracting the "categorie" values.
This can be accomplished using the program: .response[] | .categorie
Here is an example, assuming your input is in a file named "input.json":
$ jq '.response[] | .categorie' input.json
"Fish"
"Birds"
Or, if you want to gather these values as a JSON array:
$ jq - '[.response[] | .categorie]' input.json
["Fish","Birds"]

Related

Convert Value in Large JSON File to CSV

First of all, I appreciate there are lots of answers regarding dealing with large JSON files. However, I have yet to find one that encounters my scenario.
The problem I face is that I have large JSON files (12mb) that look like this:
{
"range": "Sheet1!A1:P40571",
"majorDimension": "ROWS",
"values": [
[
"new_id",
"qty",
"total_job_cost",
"total_job_revenue",
"total_job_profit",
"total_job_margin"
],
[
"34244",
"5",
"211.25",
"297.00",
"85.75",
"28.87%"
],
[
"34244",
"10",
"211.25",
"297.00",
"85.75",
"28.87%"
],
...
]
}
And I wish to extract out the values array, and convert it into a csv that would like this:
new_id,total_job_cost,total_job_revenue,total_job_profit,total_job_margin
34244,211.25,297.00,85.75,28.87%
34245,211.25,297.00,85.75,28.87%
...
However, since the values array is so large, when I try to extract it using a PHP library for JSON parsing, my server crashes when it tries to read it.
Any suggestions or tips appreciated. Thanks.
You can't read json line by line,but not with any built in libraries. I wrote a simple Json parser for another answer here
Convert structure to PHP array
I had to make a slight modification to handle "real" json" In the switch change this token
case 'T_ENCAP_STRING':
if( $mode == 'key'){
$key .= trim($content,'"');
}else{
value .= unicode_decode($content); //encapsulated strings are always content
}
next($lexer_stream);//consume a token
break;
You can test it here
http://sandbox.onlinephpfunctions.com/code/b2917e4bb8ef847df97edbf0bb8f415a10d13c9f
and find the full (updated) code here
https://github.com/ArtisticPhoenix/MISC/blob/master/JasonDecoder.php
Can't guarantee it will work but it's worth a shot. It should be fairly easy to modify it to read your file.
If the problem is simply to convert the large JSON file to a CSV file, then perhaps a jq solution is admissible. Depending on the computing environment, jq can generally handle large files (GB) breezily, and with a little more effort, it can usually handle even larger files as it has a "streaming parser".
In any case, here is a jq solution to the problem as stated:
jq -r '(.values[] | [.[0,2,3,4,5]]) | #csv' data.json > extract.csv
For the sample input, this produces:
"new_id","total_job_cost","total_job_revenue","total_job_profit","total_job_margin"
"34244","211.25","297.00","85.75","28.87%"
"34244","211.25","297.00","85.75","28.87%"
This is valid CSV, and the use of #csv guarantees the result, if any, will be valid CSV, but if you want the quotation marks removed, there are several options, though whether they are "safe" or not will depend on the data. Here is an alternative jq solution that produces comma-separated values. It uses join(",") instead of #csv:
(.values[] | [.[0,2,3,4,5]]) | join(",")

Beginner to creating and reading JSON objects

Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual

jQuery Autocomplete Remote

I'm using this http://jqueryui.com/demos/autocomplete/#multiple-remote on my website, I can see this code 'searches' search.php does anyone know what format search.php should be in and what it should look like?
Thanks,
From the page you linked, it shows you the expected data format. (pasted below) At it's simplest, you can have a print statement in the search.php file that simply echoes back some hard coded contents. A more elaborate solution is to have your search.php pull real time from a database and then format the data as expected.
Expected data format
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
So, just to get off the ground and see it working, use this line for search.php and build from there by customizing your choices or connecting to a db etc.
print '[ "Choice1", "Choice2" ]';

mongodb php $push not inserting array

I've seen a bunch of the other Mongo PHP $push questions up here on SO, but for some reason none of what they're saying is working, so I'm posting my own version.
Basically, I'm trying to follow a guideline set by 10gen where representing something like a news feed or blog/comment post should be done using buckets - making documents that hold a certain number (50) of events (comments, etc.), and then creating multiple documents as the content grows.
What I'm trying to do is push documents ($event) into an array (events), but there seems to be some confusion with PHP when the document doesn't exist (upserting). I tried to do it with an insert, but insert and $push don't play well together.
Here's what I have right now:
$historyDoc = array('_id'=>$uID, 'count'=>1,
array('$push' => array('events' => $event)));
$query = array('_id'=>$uID);
//add user to history
$collection->update($query,$historyDoc,
array('safe'=>true,'timeout'=>5000,'upsert'=>true));
Where $event is a properly-formatted array (document) of things (e.g. timestamp, userID, action, name) and $uID is a MongoID object taken from another collection.
The result that I get is this:
{
"_id": {
"$oid": "4f77ec39fef97a3965000000"
},
"0": {
"$push": {
"events": {
"timestamp": 1333259321,
"action": "achievement",
"pts": 0,
"name": "join"
}
}
},
"count": 1
}
Which is good, because my document is at least showing up right, but how the hell is there a key with a "$" in it? It's not like I'm failing to escape the $...I've been very intently using single quotes for that exact reason.
Maybe there's something I'm missing, or maybe I broke PHP, but I've been wrestling with this one for awhile and there's nothing I can thing of. It's holding my whole project up, so....>:/
Your update document is ill-formed, try this:
$historyDoc = array('_id' => $uID,
'count' => 1,
'$push' => array('events' => $event));
It's not the most elegant solution, but it looks like it works. Apparently there's a problem with using $push on a new document (insert or upsert) (EDIT: It might actually be the issue with combining atomic and non-atomic thing that's the problem. You can't use atomic operators on _id, so...). However, you can get around it by inserting the document first and then updating/upserting it.
In order to initialize an array in Mongo via PHP, you need to create a document with an empty array a a value, as seen here:
$historyDoc = array('_id'=>$uID.'-0',
'count'=>1,
'events'=>array());
From there, you can simply take what you were going to put into the first index and upsert it later:
$collection->update($query, $historyDoc,
array('safe'=>true,'timeout'=>5000,'upsert'=>true));
$collection->update($query,
array('$push'=>array('events'=>$event)),
array('safe'=>true,'timeout'=>5000,'upsert'=>true));
This yields a resulting document of the form:
{
"_id": "4f77f307fef97aed12000000-0",
"count": 1,
"events": [
{
"timestamp": 1333261063,
"action": "achievement",
"pts": 0,
"name": "join"
}
]
}
Source: Mongo PHP Manual - Updates

How to generate json response using php

How to generate json response using php
In the model:
public function groups($getGroupId) {
$cols = array('group_id','name');
$sql = $this->select ()
->from ( $this->_name, $cols )
->where ( 'parent_id=?', $getGroupId );
$groupDetails = $this->fetchAll ( $sql );
//$childGroupName = $groupDetails['name'];
return $groupDetails;
}
groupDetails.php page:
$dbGroup = new dbGroups();
$groupDetails = $dbGroup -> groups($getGroupId);
$jsonResponse = json_encode($groupDetails);
print_r($jsonResponse);
When printing the data i'm getting response like this
[{"group_id":"2","name":"ABCD"},{"group_id":"7","name":"XYZ"}]
But i want output like this, Because i have to generate a jstree using json
[
{
"data" : {
"icon" : <optional>,
"title" : <node name>
},
"attr" : {
"rel" : <the type you defined in the js (maybe "group")>,
"title" : <node title>,
"id" : <the node's id / group id>
},
"state" : "closed"
}
]
I would recommend that you use the output from json_encode as it is. Takes less bandwidth. Only reason I see for all the whitespace is for debugging, and for that I'd rather use FireBug and/or JSONView in FireFox.
Anyways, if you really want to, you can maybe try the JSON_PRETTY_PRINT flag? Seems this was added in 5.4.0 though, so maybe not the version you're on supports it... There seems to be options you can use for that in the comments there though. Maybe you can find something useful? http://www.php.net/manual/en/function.json-encode.php#102091
You say you have to create a jstree now, and that doesn't really have anything to do with what you're asking. You're two examples of data doesn't look anything alike at all. json_encode does not do anything special or magic. It just takes data and turns it into JSON. It's your job to make that data look correctly first, before encoding it. Your DB query most likely returns a set of flat rows, and you'll have to loop through it and somehow generate your tree the way you want it. You can probably find other questions here about how to create tree structures out of flat DB results.
Since you are using Zend Framework, I recommend you to use Zend_Json. Zend_Json is a pretty useful component to use in order to format Json from any supported format (object, array, xml...).
Zend_Json::decode() and Zend_Json::encode() will allow you to encode and decode Json and prettyPrint() is used to make your output prettier.
Edit:
As Svish said, your two examples doesn't look alike, so it's kind of hard to guess what you want to put inside your tree.
What you need is to create your own array, so you can make it look like the way you want.
For example, let's say you only want one row from your database in your tree, then your array would be something like this:
$v = array(
array(
"data" => array("icon" => "ICON",
"title" => $row->name),
"attr" => array("rel" => "REL",
"title" => "TITLE",
"id" => $row->group_id),
"state" => "closed"));
echo Zend_Json::encode($v);
These lines should echo something like in your examples.
To make it works with your fetchAll(), a simple foreach will do it.

Categories