What is meant by 'a valid array format for collections'? - php

When calling an REST API method I get back that there is an error
Error processing request stream. The payload must represent a valid array format for collections.
But when searching for:
valid array format for collections
I get back a lot, but nothing clarifies what is meant by this. I'm guessing the data i send is not valid (currently i'm sending an array('foo' => 'Bar')) but this is probably not correct.
Has anybody got a pointer to what is happening here? Or what i could check?
The documentation of ExactOnline (which I'm posting to) is not sufficient. It only states what fields they have, but nothing about these kind of error messages.
==========================
Ok, this needs some clarification, my bad!
As written, i'm communication with ExactOnline, via their API.
I'm calling the method to post a sales order. With that, i'm using a set of scripts Exact provides on their website (for developers).
on page:
https://start.exactonline.nl/docs/HlpRestAPIResourcesDetails.aspx?name=SalesOrderSalesOrders
under 'POST', you can read the mandatory fields, under which 'SalesOrderLines' is one of them. It does not tell me what it expects or in what format.
I wrapped my array in a json_encode and tried again, but no luck. It still tells me the same error.

I'am currently using the same ExactOnline API. Have to say that the documentation lacks in information on this topic indeed!
To make a valid array for collections you have to use the following base:
$array = array(
'InvoiceTo' => 'bc960e43-be9d-409c-9cfe-31ce56cc3238',
'SubscriptionLines' => array(
array('Item' => '7e50702b-5bbf-4b77-ab73-5dad50016e82')
)
)
The json_encode($array) on this list would be:
{
"InvoiceTo":"bc960e43-be9d-409c-9cfe-31ce56cc3238",
"SubscriptionLines":[
{"Item":"7e50702b-5bbf-4b77-ab73-5dad50016e82"}
]
}
So the important part here is to do array(array()) inside the SubScriptionLines. This tells the JSON that you want to use an JSON Array instead of the JSON Object notation.
For your particular question you need to change the keys into the keys given in the documentation for a SalesOrder. Not all manditory fields of the api are included here, because this solution is for Subscriptions. However, the principle will be the same.
Hope this will help you and others implementing the exact API fully :)

How are you serializing your payload? If it is meant to be in JSON format, a collection would look like this:
[
{
"foo": "bar"
},
{
"foo": "baz"
}
]

Related

PHP, Laravel: Eliminate Specific Complex Array from JSON

I'm currently developing an API using Laravel for my project, the concept:
Retrieve JSON data from MySQL.
Receive user input from the Front-end (string).
Convert both JSON and string input into an array with similar structure. The array structure here is basically ["ObjectA", "ObjectA_quantity", "ObjectB", "ObjectB_quantity", ...].
Basically, eliminate the quantity of every object of Database's Array, based on every object that User Input's Array got. For example, if the Database's Array got ["pizza", "1", "burger", "2"], and the User Input's Array got ["pizza", "1"], the output of the method is expected to be ["burger", "2"].
The method that I developed will give inconsistent and confusing output, like for some object, it works well, for other it doesn't eliminate anything and if the User Input's Array too big (> 1 object), it also doesn't eliminate anything. I really welcome different approach or anything else that will give the expected output as above. Thank you very much
Here's the source code of the method I've develop: (method's located on: else if ($transactionGetter->type == 'return'), Line 148 and so forth)
https://github.com/andre-nk23/packme-backend/blob/master/app/Http/Controllers/API/TransactionController.php
if it's a JSON you must decode the value before access
$transactionGetter=json_decode($transactionGetter);

Get specific value of array object

I have an array object below
33 => 'a:2:{
s :8:"latitude";
s:10:"39.3600586";
s:9:"longitude";
s:18:"-84.30993899999999";
}'
And here is the variable I'm using to get the value of that object
$events_location = $entries[1]['33'];
Is there a way to get just the value of either the latitude or longitude instead of everything in the single quotes?
Thanks!
What you have here is a serialized string. Unserialize it to access the key in the array:
$events_location = unserialize($entries[1]['33']);
echo $events_location['longitude'];
This should be a comment but its a bit long.
The string you have shown us looks vaguely like part of a serialized php entity. But it's not. If you try to unserialize this you'll get an error. The underlying data appears to be a coordinate - but even ignoring the syntactic errors, the semantics of the structure are wrong.
Please check the source you transcribed this from. If you have not copied the original content here please amend your question.
If you have transcibed it correctly then go speak to whoever supplied you with this data and ask them to fix it.

How to return an array instead of object in JSON response?

I've one working REST API developed using Slim PHP framework.
It's working absolutely fine.
The only issue is when there is no error present i.e. an array $errors is empty it comes as an array in JSON response but when the array $errors contains any error like $errors['user_name'] then it comes as an object in JSON response.
Actually I want to return the array when error is present. How should I do this? Can someone please help me in this regard?
Thanks in advance.
When your $errors is not empty, pass it through json_encode and echo it.
It will give you JSON object in return,
then convert JSON object into JavaScript array. (see the following code.)
var o = {"0":"1","1":"2","2":"3","3":"4"}; // your response object here
var arr = Object.keys(o).map(function(k) { return o[k] });
console.log(arr);
Recently got a close issue with Symfony's JsonResponse::create()
Turns out arrays with index not starting at 0 will be encoded into objects, as well as arrays with "holes", and probably any array with at least one non-int key.
In other word, arrays with anything else than consecutive numeric keys starting from index 0 seem to be encoded as object.
I guess this is designed to avoid sending big empty arrays when you map a handful of datas with big indices like [14334, 839493, 246193], and is probably documented somewhere.
Learning if this is a Symfony of json_encode behavior from comments would be welcomed addition :)
Note : Even if you return an array, it seems necessary to wrap it in an object for GET request to prevent some XSSI and JSON-JavaScript Hijacking.

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.

Don't understand serialize()

I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?
Basically, the goal of serialize is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}
And, later, you can unserialize that string, to get the original data back :
$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
Ability to transmit (almost) any kind of PHP data from one PHP script to another
Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings
Note, though, that using serialize is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode and json_decode), ...
In the PHP manual, you can also read the Object Serialization section, btw.
If you want to save an array or object normalised in a database row for example, serialize() (and unserialize()) are your friends, because you can't store an array or object flattened without first turning it into a string.
json_encode() and json_decode() are similar except they encode as JSON.
See this example, should be pretty clear.

Categories