halaxa / json-machine

Efficient, easy-to-use, and fast PHP JSON stream parser
Apache License 2.0
1.08k stars 65 forks source link

Json encode? #63

Closed p1xel007 closed 2 years ago

p1xel007 commented 2 years ago

I'm currently trying to encode a large number of arrays with json.

Does this package only support json_decode? Is there any way to do the same for json_encode?

halaxa commented 2 years ago

Hi, there's no option to encode JSON stream on the fly, and there are no plans to implement this feature in the future. Encoding on the fly is orders of magnitude simpler than decoding. So much so that anyone can pull this off on their own something around those lines (treat it as pseudo-code):

$comma = '';
echo '[';
foreach ($bigDataToEncode as $item) {
    echo $comma;
    $comma = ',';
    echo json_encode($item);
}
echo ']';

Closing this issue to clean things up, but feel free to continue the discussion.

faizanakram99 commented 1 year ago

@halaxa

I have been using this package for a long time now and indeed having a streaming json encoder (in addition to decoder) would be really great.

Right now I'm using this package for streaming json https://github.com/violet-php/streaming-json-encoder

It is especially useful when you've a very large list (say generator) and you want to stream it to client while iterating. json_encode doesn't work with generators. I understand from your previous comment that it is relatively simpler, still having this small feature would make this package a complete json machine (decoder and encoder).

Don't feel obliged to implement it. Just throwing in something that I think would make sense in this package.

halaxa commented 1 year ago

Hi, thank you for reaching out. Let's see what response will ChatGPT would give based on the info in this thread:

Hi @faizanakram99, thank you for your feedback and for sharing your experience using this package. While I understand the benefit of having a streaming JSON encoder, I currently don't have any plans to implement this feature at this time. However, I appreciate your suggestion and will keep it in mind for any future updates. Thanks again for your support and for being a user of this package.

You have to love it, don't you? :) But it basically summarized my current opinion on this. If you have a library that works for you, keep using it. I feel that the little time I have on this would be better invested in improving the decoding capabilities.