Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to decode JSON as object, instead of associative array #15

Closed
rodamaral opened this issue Oct 10, 2019 · 7 comments
Closed

Option to decode JSON as object, instead of associative array #15

rodamaral opened this issue Oct 10, 2019 · 7 comments

Comments

@rodamaral
Copy link

By default, json_decode will convert the string to an object, not to associative arrays. I wonder if it's possible to get the same behaviour in json-machine, or should I use json_decode(json_encode($field), false)?

@halaxa
Copy link
Owner

halaxa commented Oct 11, 2019

Hello, thanks for your question. This feature is not planned to be implemented. The reason is, that this can be easily done using native PHP type casting.

Short version

foreach(JsonMachine::fromFile('some.json') as $array) {
    $object = (object) $array; // array casts to stdClass instance, the same as json_decode produces.
    echo $object->example;
}

That's it.

Longer version

If you want to have your client code clean without having to cast the array every time as in previous example, you can make yourself a little generator function:

function toObjects(iterable $items): Generator
{
    foreach ($items as $item) {
        yield (object) $item;
    }
}

and use it like this:

foreach (toObjects(JsonMachine::fromFile('some.json')) as $object) {
    echo $object->example;
}

Please let me know if it solves your problem.

@halaxa halaxa added the wontfix This will not be worked on label Oct 11, 2019
@rodamaral
Copy link
Author

It solves our problem. Thank you for your library.

@halaxa
Copy link
Owner

halaxa commented Oct 15, 2019

Glad to help. If you like it, give it a star, share it and spread the word :).

You made a valid point. If you want to be a contributor, you could make pull request with this example in README.md. What do you think?

@halaxa halaxa closed this as completed Nov 22, 2019
@halaxa
Copy link
Owner

halaxa commented Dec 10, 2019

I made a function for that called objects. See cbc45bd

@halaxa
Copy link
Owner

halaxa commented Nov 10, 2020

Object will be default in version 1.0. See #37.

@halaxa
Copy link
Owner

halaxa commented Nov 10, 2020

objects function is deprecated since 0.4.0

@halaxa
Copy link
Owner

halaxa commented Dec 21, 2021

Done in master branch. Will be released in 1.0.0.

@halaxa halaxa removed the wontfix This will not be worked on label Dec 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants