Mongo result as JSON - php

Using following code to convert as document to JSON is:
print( json_encode((new MongoClient())->db->col->findOne()));
//Output:{"_id":{"$id":"52838520f7c255c009000000"},"test":"test"}
Is there any way to set Mongo to return _id field as string instead of object? Is it safe to return _id value to client side script (as the response of a GET request)
I do not want manually convert _id to string and vice versa when implementing a REST api.

No, there is nothing you can do (mongod in comparison to SQL can not do modification of the fields it is outputting). Therefore you only resort is to do what you didn't want to do (manually convert). But it is not hard, all you need to do is one of these:
(string)$doc['_id'];
(string)$doc->_id;
$doc['_id']->{'$id'};

Related

What is the substring equivalent in PHP

I am getting JSON files but each file has a code/ID with it, in the beginning
i am trying to make a standard way to crop the strings no matter how the code/ID changes.
so these are 2 JSON files:
a:12{/*JSON DATA HERE*/}
a:130 {/*JSON DATA HERE*/}
a:1 {/*JSON DATA HERE*/}
i did not find a way to locate the first occurrence of "{" and include it in the new string that will also include the rest of the JSON string.
in JAVA it would go something like that, but i need it in php:
String myjson = "a:130{/*JSON here*/}";
String newjson = myjson.substring(myjson.indexOf("{"), myjson.length());
how can i do that in php?
This really seems to be a PHP serialized array (through serialize / unserialize) and not JSON.
PHP uses a:<count>{...} to indicate a serialized array in its format.
If you can trust the data (i.e. not user submitted but generated by a trusted application), don't parse it yourself and use unserialize instead.
The reason why you never should use unserialize on user submitted data that you can't verify independently is that it is able to create objects of a user specific selection, and if the object defines __wakeup, it might be able to coerce the object into performing any operation the attacker want. This is also why there is a large warning on the unserialize manual page.

Manipulate/Edit a json encoded string value in a database row

I'm working with laravel 4 and the eloquent implementation.
I want to edit/manipulate a value in a database field which contains a json encoded string.
Example: I have a database row with the name "meta". The value of "meta" is a json encoded string.
The example json encoded string:
{"name":"steven","lastname":"builder"}
How can I manipulate the value of that json string?
For example "name" ?
I've found mutators but I dont know how to work with them.
http://laravel.com/docs/eloquent#accessors-and-mutators
This works like most ORM's in that you simply make the change like you would to a normal object's properties, and just save the changes. In this example:
You've already got who you want to update, so we'll just call that object $meta, and you've already manipulated your json, so we'll call it $manip_json, and we'll say the column name is just meta_col
$meta->meta_col = $manip_json;
$meta->save();

An alternative to returning a delimited string?

I have a whole suite of PHP scripts that interact with both the Android and iOS version of a mobile app. They all work the same: After the mobile app initiates a GET or POST, the PHP script typically returns a dash delimited string.
e.g.
If I want to get a list of the comments on a particular page, the PHP script would return something like
user1-comment1-user2-comment2
Is there a better way than this? Because if I ever want to return a new variable e.g.
user1-comment1-newValue1-user2-comment2-newValue2
then this will break all current versions of the mobile app.
Why not serialize the result and parse it in java? You could also use json_encode in PHP and decode it in your android app... see How to parse JSON in Android
You need to use a serializer. If you have a user name that contains a - you'll run into problems. Serializers take care of this for you. The current favorite is JSON, used to be XML.
JSON has excellent support in most web languages.
You can serialize your array of data into either a json string or a message pack string. Let's say your php array was:
$a = array(
"user1" => "comment1",
"user2" => "comment2",
"user3" => "comment3"
);
That would translate to this in json:
{
"user1": "comment1",
"user2": "comment2",
"user3": "comment3"
}
This json string can be easily converted to NSDictionaries on ios (using NSJSONSerialization) and JSONObjects on android (tutorial here).
A message packed string would be similar in structure to the json string above, but is less human readable because of its more compact nature. However, both Java and Objective-C have libraries to help translate messaged packed data into native objects.
Using JSON, you can make use of name/value pairs, so the order or inclusion of the parameters won't matter. JSON also provides hierarchy and limited typing, such as number versus string.
JSON also allows you to easily escape characters, so you could have any value you want (even with backslashes and quotes.

PHP multidimensional array to JSON

So im trying to figure out the best way to get MySql table data into either a multidimensional PHP array or convert that multidimensional array into a json string.
Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction.
I want to assign multiple values to the same key, for example:
[{"key1": "package1", "package2", "package3"}, {"key2": "package1", "package2", "package3", "package4"}]
I think that is not going to work right? Because i dont have any type of index's?
That is not valid JSON. The structure you are looking for would be something like:
[
{"key1": ["package1", "package2", "package3"]},
{"key2": ["package1", "package2", "package3", "package4"}]
^ An array as the value to the key "key1", "key2", etc..
]
At the PHP side, you would need something like:
For every row fetched from MySQL
$arr[$key] = <new array>
for each package:
append package to $arr[$key]
echo out json_encode($arr)
JS arrays have an implicit array keying, starting at index 0. What you've got is a perfectly valid JS array, the equivalent of having written:
var x = []; // create new empty array
x[0] = {"key1": .... }; // first object
x[1] = {"key2": ....} // second object
Note that the contents of your {} sub-objects is NOT valid.
You should never EVER built a JSON string by hand. It's too unreliable and easy to mess up. It's just easier to use a native data structure (php arrays/objects), then json_encode() them. Ditto on the other end of the process - don't decode the string manually. Convert to a native data structure (e.g. json_decode(), JSON.parse()) and then deal with the native structure directly.
essentially, JSON is a transmission format, not a manipulation format.

Using null value from SQL Server in iOS, PHP and JSON

The application I am designing consumes JSON objects returned by PHP scripts that select from a SQL Server 2008 database. The problem I am encountering is that when the database is missing a value for a certain field, it returns as a null in JSON. Then when the app parses the JSON (I am using NSJSONSerialization), the dictionary contains a value. When using this dictionary to populate my view, the application crashes when encountering the null value.
What would be the easiest way to bypass this problem? I am thinking I could just replace all nulls with empty string before the PHP returns the data as JSON; however, that might not be the best solution. Is there a simple way to check in iOS?
Thanks for the help.
To check for null values you need to see if the object is [NSNull null].
id object = [dict objectForKey:#"key"];
if(object == [NSNull null])
{
//Handle null value
}

Categories