Hacker News new | ask | show | jobs
by ranger_danger 337 days ago
I can't believe they still don't have a way to parse JSON responses automatically.

If you combine e.g. hx-post with hx-target, then it will put the text from the response into the target selector... but there is no "hx-source" to select what part of the response to use.

I'd really love to be able to set e.g. hx-source="somejsonfield" instead of having to manually handle the response with a custom function that parses/error checks the json and then sets the selector's text to the value of a json key. It could really save a lot of boilerplate code IMO.

2 comments

The philosophy of HTMX is not to send JSON, but HTML fragments.
They didn't mention sending JSON though... and you can absolutely return HTML fragments in a JSON response.
Then what's the point of using HTMX?

If you're not sending just exactly the necessary HTML to replace the target's HTML; if you need to parse JSON, then even jQuery would be better suited.

The whole idea of HTMX is to get rid of the extra steps.

I don't always have control over the remote end or due to business reasons the format can't be changed.

And since htmx also has template plugins, being able to feed JSON values into it makes sense to me... a similar project, EHTML has this feature.

You would use htmx when you control your backend server. Otherwise, you would use something else.
But why?
Fetching data from APIs I have no control over, or ones that serve multiple purposes and use a single response format
HTMX uses HTML snippets over the wire to replace HTML elements on the client. It's not supposed to grow to support every use case you can imagine.

If you're calling APIs that you have no control over, you do so on your server.

That's the entire point of HTMX: the minimal necessary addition to browsers/HTML to allow HTML REST APIs to update pages without full page loads.

Personally, I wouldn't consider HTMX to be a good fit for those scenarios.

Obviously you _could_, and it might even work well, but I think that's using the tool against its grain.

I guess I could see it for decoupling your need to control the API you're using. The case where you have an existing API, whether your own or someone else's, and just want to get a new frontend hooked up to it.
Just put any template rendering engine in-between.

Htmx is "bring your own backend", but you do have to have a backend, be it Haskell or Zig or Gleam, that talks to your API, and renders HTML.

htmx is hypermedia oriented, so we expect hypermedia responses from the server

we do have a json extension for handling JSON responses, but it's a step away from the hypermedia architecture:

https://github.com/mariusGundersen/htmx-json