When simply returning $users, I get the exact same result with toArray() and json_decode().
But when looping $users in my view, I get an error ('Trying to get property 'xxx' of non-object) with the toArray() method. Not with json_decode(). Any idea why? I'm on Laravel 6.
$client = HttpClient::create();
$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/users');
$users = json_decode($response->getContent());
// $users = $response->toArray();
return $users;
The toArray() method return pure array. While json_decode() keys are always strings, while the value can be a string, number, true or false, null or even an object or an array.
Therefore, you are trying to access an object returned by json_decode which works if you have objects while encoding it. But, while trying to access an object from array perspective it will not work because arrays are plain array.
Explanation of Json_decode()
PHP's json_decode function takes a JSON string and converts it into a PHP variable. Typically, the JSON data will represent a JavaScript array or object literal which json_decode will convert into a PHP array or object.
Explaining PHP array is beyond this scope. However:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Finally,
You are trying to access an object returned by json_decode - works fine. But an array will not hold objects such that it throws that trying to get property of non-object.
Related
I have a project I'm working on that implements MySQL, React and Express.js. I need to save an array into MySQL, but there are currently no ways to save an array, as far as I could see, so I was forced to convert it into a string. When I get it back from Express to the client, it's obviously a string, so I can't access the data. This array is used for a graph, mainly. What are some of the ways I can convert this string back to an array?
You can use JSON.parse() to convert a string into an array.
const response = "[1,2,3]";
console.log(JSON.parse(response));
You can store your json object (including arrays )in form of text in mysql database.What you have to do is JSON.stringify("your array") and persist it in database.And while you are retrieving it back from database you can JSON.parse() to get it in form of JavaScript object
Depends on how you formed the string. If you used , for joining the elements, then you can use javascript's string.split() method.
let str = '1,2,3,4';
let arr = str.split(',');
Just pass in whatever delimiter you used to join the elements.
OR
If you're saving elements as a json string, then use JSON.parse(str) as shown by Nils Kähler in his answer
I'm trying to create a json with multiple records by following this example: Generate a sample JSON with an array in it in Delphi XE5
must be the same way, except that when I add the array to the object
JSonObj.AddPair (TJSONPair.Create ('records', TJSONArray));
returns the error:
"There is the overloaded version of 'Create' that can be called with arguments These"
How do I add to the array object?
If I convert an array to string and add, to receive the amounts can not treat as an array ...
You're passing it the class reference for a JSON array. You need to pass it an instance.
arr := TJSONArray.Create;
JSONObj.AddPair(TJSONPair.Create('records', arr));
Look carefully at the answers in the question you link to, and you'll see this is exactly what they're doing, too.
I want to serialize entity object in my Symfony2 application to JSON object (I have to pass it to ajax function and use it in my javascripts).
Everything works fine but I have in my entity object addresses which are PersistentCollection object. Then if I serialize them in normal way field "adresses" has got empty Object. I figured out that I can set "LimitedRecursiveGetSetMethodNormalizer" to "1" and then PersistentCollection is being serialized. The problem is that I've got this object serialized, not array with my addresses so I can't use them in my javascript because they are not there...
\Cloud\ApplicationBundle\Resources\LimitedRecursiveGetSetMethodNormalizer::$limit = 1;
$businessJson = $this->get('serializer')->serialize($business, 'json');
Variable $business is of course Entity Object. I hope that my question is clear.
I have to add that I know that i can convert PersistentCollection object to Array and then serialize it to Json but this way i would have to pass my entity and adresses in seperate variables. I would prefer to do it one variable.
Thanks for any help !
How should I handle json returned as array in Backbone.Collection's overridden parse?
I used the following for json returned as object:
parse: function(response) {
return response.results;
}
What about when json gets returned as array?
Backbone, by default, expects an array. If the array is nested within an object, you need to over-ride parse() as you have done above. However, if the response returns an array, you don't need to do anything (since that is what backbone is expecting). Finally, if you are expecting a mix of the two (that is, might be an array sometimes and might be an object the other times, see dbaseman's answer).
I'm using built-in functionality to create JSON string in Flash app.
Here example of my source code
objStr = JSON.stringify(
{
version:"1.0",
skin:"white",
palette:{dataColor:"#0397d6",negativeDataColor:"#d40000",toolbarColor:"#056393"}
});
I have a problem. Every time I've started my app (not executing createJSON function), I have different member order in JSON string as result.
For example:
{"version":"1.0","palette":{"negativeDataColor":"#d40000","dataColor":"#0397d6","toolbarColor":"#056393"},"skin":"white"}
or
{"palette":{"negativeDataColor":"#d40000","toolbarColor":"#056393","dataColor":"#0397d6"},"version":"1.0","skin":"white"}
How can I fix it.
JSON objects are unordered, see JSON.org:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array. An object is an unordered set of name/value pairs
An ordered list of values. In most languages, this is realized as an
array, vector, list, or sequence. An array is an ordered collection of values.
Order really doesn't matter since you should be retrieving the values by the key rather than iterating over them.