-1

Can I use a filter condition in python -mjson.tool command to select objects which has specific attributes?

For example, I have a sample.json file with for objects out of which two has an attribute "test": "pi". And I need to fetch only those two objects.

0

I believe the answer is no. I'm not a python expert, but I have looked at the code. I don't see any options to that tool.
I've had this same issue lately, and I've just piped to grep what I am looking for. grep will allow you to see line Before and/or After the mathching line, so you can see the whole clause.
... | pythom -m json.tool | grep -E -B 3 -A 5 'test.*:.*pi'
This will show 3 lines before and 5 lines after any line that has 'test' [something] : [something] pi

  • I will try and let you know. Thanks for the details. – Kumarjit Ghosh Mar 1 at 9:39
0

Nested data structures (like JSON) have to be parsed by relevant tools (e.g. json-aware here) in order to extract the information properly. Trying to operate on the nested data structures with line-aware routines only (like grep/sed/awk/etc), will produce failures and false positives. E.g., the above answer only would work if your JSON was pretty-printed having each JSON element one per line. Though it would fail if JSON was printed somehow else (i.e. in one line, or having multiple elements on the same line).

Thus, if you use python, you have to parse the object and then extract required data programmatically (i.e. write a script in python).

However, there's another approach: for unix there's a number or json-aware utilities developed to achieve the ask like yours quite easily, e.g. jq, jtc (and many others). Here, let me show you the solution based on jtc:

Assuming you have a following json:

bash $ cat file.json 
{
   "Root": [
      {
         "data": "2.71",
         "test": "e"
      },
      {
         "data": "3.14",
         "test": "pi"
      }
   ]
}
bash $ 

then, in order to extract all the objects which contain "test": "pi", using jtc is like this:

bash $ cat file.json | jtc -w'[test]:<pi>: [-1]'
{
   "data": "3.14",
   "test": "pi"
}
bash $ 

explanation on the walk-path (-w) parameters:

1. [test]:<pi>: will find all elements like "test": "pi" (if there are multiple)

2. [-1] will step up 1 JSON tier from found element(s).

resulting walk(s) will be printed.

Consult jtc complete user guide here: https://github.com/ldn-softdev/jtc/blob/master/User%20Guide.md

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.