Repository: home-assistant/core
Pull request: JSON serialize NamedTuple subclasses with aiohttp


## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->
JSON serialize NamedTuple subclasses

## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [x] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #74934
- This PR is related to issue: 
- Link to documentation pull request: 

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [ ] The code change is tested and works locally.
- [ ] Local tests pass. **Your PR cannot be merged unless tests pass**
- [ ] There is no commented out code in this PR.
- [ ] I have followed the [development checklist][dev-checklist]
- [ ] The code has been formatted using Black (`black --fast homeassistant tests`)
- [x] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
- [ ] Untested files have been added to `.coveragerc`.

The integration reached or maintains the following [Integration Quality Scale][quality-scale]:
<!--
  The Integration Quality Scale scores an integration on the code quality
  and user experience. Each level of the quality scale consists of a list
  of requirements. We highly recommend getting your integration scored!
-->

- [ ] No score or internal
- [ ] 🥈 Silver
- [ ] 🥇 Gold
- [ ] 🏆 Platinum

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [ ] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io


Problem statement:
Type is not JSON serializable: RGBColor
### The problem

I use an automation/script to randomly select a color for an RBG light strip using `color_name` for a `light.turn_on` service.  This worked find until I updated to 2022.07.x.

What's weird is that the same service call works fine in the service call tab of the frontend.  It only doesn't work with automations/scripts.

### What version of Home Assistant Core has the issue?

2022.07.x

### What was the last working version of Home Assistant Core?

2022.06.x

### What type of installation are you running?

Home Assistant Container

### Integration causing the issue

Script/Automations/Websocket

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

```yaml
- service: light.turn_on
      data:
        entity_id: light.under_bed
        color_name: >
          {{ [ "Red", "Green", "Blue", "Purple" ] | random }}
        brightness: 60
```


### Anything in the logs that might be useful for us?

```txt
Logger: homeassistant.components.script.bedtime
Source: helpers/aiohttp_client.py:101
Integration: Script (documentation, issues)
First occurred: 12:07:49 PM (2 occurrences)
Last logged: 12:16:28 PM
 
Bedtime: Error executing script. Unexpected error for call_service at pos 3: Type is not JSON serializable: RGBColor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 447, in _async_step
    await getattr(self, handler)()
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 680, in _async_call_service_step
    await service_task
  File "/usr/src/homeassistant/homeassistant/core.py", line 1713, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1750, in _execute_service
    await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)(
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 204, in handle_service
    await service.entity_service_call(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 680, in entity_service_call
    future.result()  # pop exception if have
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 930, in async_request_call
    await coro
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 717, in _handle_entity_call
    await result
  File "/usr/src/homeassistant/homeassistant/components/light/__init__.py", line 553, in async_handle_light_on_service
    await light.async_turn_on(**filter_turn_on_params(light, params))
  File "/usr/src/homeassistant/homeassistant/components/wled/helpers.py", line 17, in handler
    await func(self, *args, **kwargs)
  File "/usr/src/homeassistant/homeassistant/components/wled/light.py", line 246, in async_turn_on
    await self.coordinator.wled.segment(**data)
  File "/usr/local/lib/python3.10/site-packages/wled/wled.py", line 481, in segment
    await self.request("/json/state", method="POST", data=state)
  File "/usr/local/lib/python3.10/site-packages/backoff/_async.py", line 133, in retry
    ret = await target(*args, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/wled/wled.py", line 178, in request
    response = await self.session.request(
  File "/usr/local/lib/python3.10/site-packages/aiohttp/client.py", line 408, in _request
    data = payload.JsonPayload(json, dumps=self._json_serialize)
  File "/usr/local/lib/python3.10/site-packages/aiohttp/payload.py", line 398, in __init__
    dumps(value).encode(encoding),
  File "/usr/src/homeassistant/homeassistant/helpers/aiohttp_client.py", line 101, in <lambda>
    json_serialize=lambda x: orjson.dumps(x).decode("utf-8"),
TypeError: Type is not JSON serializable: RGBColor
```


### Additional information

_No response_

Hints from issue discussion:

Commit message: order matters

Patch to review:
diff --git a/homeassistant/helpers/json.py b/homeassistant/helpers/json.py
index 74a2f542910f4..3181558092d5b 100644
--- a/homeassistant/helpers/json.py
+++ b/homeassistant/helpers/json.py
@@ -2,7 +2,7 @@
 import datetime
 import json
 from pathlib import Path
-from typing import Any, Final
+from typing import Any, Final, NamedTuple
 
 import orjson
 
@@ -41,6 +41,8 @@ def json_encoder_default(obj: Any) -> Any:
         return obj.as_dict()
     if isinstance(obj, Path):
         return obj.as_posix()
+    if isinstance(obj, NamedTuple):
+        return tuple(obj)
     raise TypeError
 
 
diff --git a/tests/helpers/test_json.py b/tests/helpers/test_json.py
index 54c488690faef..a2cd52f4a11ae 100644
--- a/tests/helpers/test_json.py
+++ b/tests/helpers/test_json.py
@@ -2,6 +2,7 @@
 import datetime
 import json
 import time
+from typing import NamedTuple
 
 import pytest
 
@@ -96,3 +97,16 @@ def test_json_dumps_tuple_subclass():
     tt = time.struct_time((1999, 3, 17, 32, 44, 55, 2, 76, 0))
 
     assert json_dumps(tt) == "[1999,3,17,32,44,55,2,76,0]"
+
+
+def test_json_dumps_named_tuple_subclass():
+    """Test the json dumps a tuple subclass."""
+
+    class NamedTupleSubclass(NamedTuple):
+        """A NamedTuple subclass."""
+
+        name: str
+
+    nts = NamedTupleSubclass("a")
+
+    assert json_dumps(nts) == '["a"]'


Code review comments:
diff_hunk: @@ -41,6 +41,8 @@ def json_encoder_default(obj: Any) -> Any:
         return obj.as_dict()
     if isinstance(obj, Path):
         return obj.as_posix()
+    if isinstance(obj, NamedTuple):
+        return tuple(obj)
path: homeassistant/helpers/json.py
text: @user1:
This is not covered by tests because `isinstance(obj, (set, tuple))` will match on namedtuples

@author:
It works better if I change it in the right place.