PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

[FIXED] how to get parent key by child value with jq

 July 25, 2022     jq, json     No comments   

Issue

I have this example json:

{
    "Server monitoring - Disk, Memory, CPU": {
        "alerts": {
            "d_usage_65": {
                "title": "D Usage 65 | #site"
            },
            "d_usage_75": {
                "title": "D Usage 75 | #site"
            }
        }
    },
    "Categoty 2": {
        "alerts": {
            "thread_count_50": {
                "title": "Thread Count above 50 | #site"
            },
            "upload_manager_thread_count_100": {
                "title": "Thread Count above 100 | #site"
            }
            
        }
    }
}

I am trying to get "d_usage_65" for input "D usage 65 | #site". This is what I have tried:

.[] | .alerts | select(.[].title == "D Usage 65 | #aidoc_site") | keys

but it returned:

[
  "d_usage_65",
  "d_usage_75"
]

Solution

You can access keys and values at once using to_entries. For instance:

.[] | .alerts | to_entries[] | select(.value.title == "D Usage 65 | #site").key
d_usage_65

Demo

Another approach could be using tostream:

.[] | .alerts | tostream | select(.[1] == "D Usage 65 | #site")[0][0]
d_usage_65

Demo



Answered By - pmf
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing