我有一列“值”,类型为 postgres“JSON”。 值 列中的示例数据。
- “显示名称 1”
- {"middleName": "其他"}
- [{"primary": true, "type": "work", "value": "rusr@r.com"}, {"primary": true, "type": "work", "value": "iu@n.com"}]
我知道我可以像这样使用键值对访问 json,
.filter(Values.value['middleName'].astext=='other')
(values 是模型名称)
问题是如何访问字符串值或对象数组。
我试过了,
.filter(Values.value.astext=='displayname1')
它给我 AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Values.value has an attribute 'astext'
和
.filter(Values.value['type'].astext=='work')
- 我在这里尝试过滤数组中的“type”:“work”对象。你怎么做到这一点。是否可以在不指定索引的情况下搜索所有对象。
我正在使用 postgres 作为后端数据库。
模型 -
class Values(db.Model):
__tablename__ = 'attribute_values'
id = db.Column(db.Integer, primary_key=True)
attribute = db.Column(db.Integer, ForeignKey('attributes.id'), primary_key=True)
value = db.Column(JSON)
class Attributes(db.Model):
__tablename__ = 'attributes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
user_attribute = db.relationship(Values, backref='attributes', primaryjoin=id == Values.attribute)
查询我正在尝试-
db.session.query(Values).join(Attributes, Values.attribute == Attributes.id).filter("what filters that i should be using for the cases mentioned above").all()
最佳答案
假设json对象是一个字符串,使用json.loads将其转换为字典然后正常索引。
>>> import json
>>> s = """[{"primary": true, "type": "work", "value": "rusr@r.com"}, {"primary": true, "type": "work", "value": "iu@n.com"}]"""
>>> my_dict = json.loads(s)
>>> my_dict[0]['type']
'work'
然后您可以使用以下列表理解搜索 type == 工作的任何行。
>>> search = [i for i in my_dict if i['type'] == 'work']
>>> search
[{'primary': True, 'type': 'work', 'value': 'rusr@r.com'}, {'primary': True, 'type': 'work', 'value': 'iu@n.com'}]
这是不使用列表推导式的同一事物的示例。
>>> search = list()
>>> for i in my_dict:
... if i['type'] == 'work':
... search.append(i)
...
>>> search
[{'primary': True, 'type': 'work', 'value': 'rusr@r.com'}, {'primary': True, 'type': 'work', 'value': 'iu@n.com'}]
关于python - 访问在 sqlalchemy 中没有 key 的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63916064/