目前正在postgres 9.3中首次使用JSON字段,并且我在查询数组时遇到了一些困难.
具有JSON数组数据类型的字段称为"帐户",一些示例数据如下所示
[{name: "foo", account_id: "123"}, {name: "bar", account_id: "321"}]
Run Code Online (Sandbox Code Playgroud)
我希望能够找到拥有account_id 123的公司的ID.我目前遇到问题的查询如下:
select id from companies where json_array_elements(accounts)->>'account_id' = '123'
Run Code Online (Sandbox Code Playgroud)
这会导致错误:
WHERE的参数不能返回一个集合
给定以下哈希结构,我想走结构并使用"link"键修改所有值:
{"page_id":"12345", "link_data":{"message":"test message", "link":"https://www.example.com", "caption":"https://www.example.com", "child_attachments":[{"link":"http://www.example.com", "name":"test", "description":"test", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xap1/t45.1600-4/10736595_6021553533580_1924611765_n.png"}, {"link":"http://www.example.com", "name":"test", "description":"test", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xaf1/t45.1600-4/10736681_6021625991180_305087686_n.png"}, {"link":"http://www.example.com", "name":"test", "description":"test 2", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xfp1/t45.1600-4/10736569_6020761399780_1700219102_n.png"}]}}
Run Code Online (Sandbox Code Playgroud)
我一直在玩的方法对我来说感觉有点不对,我要检查所有值,看看它们是否有匹配应该是URL的模式,然后在那时修改它:
def find_all_values_for(key)
result = []
result << self[key]
self.values.each do |hash_value|
if hash_value.to_s =~ URI::regexp # if the value looks like a URL then change it
# update the url
end
end
end
Run Code Online (Sandbox Code Playgroud)
因此,转换的确切最终结果应该与URL的修改相同.我真正想要做的是将跟踪参数添加到散列中的每个URL.
我已经玩弄了将哈希转换为字符串并在其上执行一些字符串替换的想法,但这似乎不是这种做事最干净的方法.
干杯