Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

ruby on rails - Search over a nested / multi-level Postgres JSON type using Active Record

Suppose I have the json object below

:response_body => {
    "status" => "ok",
    "um" => {
        "a" => "a",
        "b" => {
            "c" => "ok"
        }
    }
}

Example search:

LogService.where(response_body: {"status" => "ok"})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using the Postgres as database and the column really is a json type, you can use a search in Rails like this:

LogService.where("response_body#>>'{status}' = 'ok'")

This #>> will walk over the json path and make the search. If you use only #> (with just one >), it will return the remaing json.

Another example, if you want to get the "c" => "ok"

LogService.where("response_body#>>'{um, b, c}' = 'ok'")

I think that′s it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...