'cannot extract elements from a scalar
I have 2 tables company and contacts. Contacts has addresses JSONB column. I tried a select statement with a join on contacts.linked_to_company and using jsonb_array_elements(company.addresses) but I get error 'cannot extract elements from a scalar' which I understand is because some entries do have [null] in column address. I have seen answers to use coalesce or a CASE statement. Coalesce I could get to not work and CASE example is in the select statement how do use it in a join? Here is the sql
SELECT company.id,
trading_name,
nature_of_business,
t.id contactID,
address->>'PostCode' Postcode,
position_in_company
FROM contact t FULL JOIN company ON (t.company_linked_to = company.id ),
jsonb_array_elements(t.addresses) address
WHERE
t.company_linked_to ='407381';
here is example jsonb
[{"PostCode":"BN7788","Address":"South Street","AddressFull":"","Types":[{"Type":"Collection"}]}]
Solution 1:[1]
The dictionaries store a reference to the list for each key here (because lists are mutable). If you copy the lists, the problem goes away
a={'a':[1,2],'b':[3,4]}
b={key:a[key].copy() for key in a}
b['b'][0]=5
Solution 2:[2]
In b, when you say a[key], the value of that key is pointing to the same list which the value of relevant key in dictionary a points to. Instead you can do a deep copy. It takes care of any level of nesting for containers.
from copy import deepcopy
a = {'a': [1, 2], 'b': [3, 4]}
b = deepcopy(a)
b['b'][0] = 5
print(a)
output:
{'a': [1, 2], 'b': [3, 4]}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kraigolas |
| Solution 2 |
