Sushant
Sushant

Reputation: 1

Python JSON Parsing through list and check condition

I have the below JSON output in python , I want to read through the list and find the value of Index which is not equal to "alias": "READ_PRD" and "alias": "WRITE_PRD" and "alias": ".kibana" and store the value in a variable.

In below case It is same value twice so store only once else store both the values.

How do I achieve this.

[
  {
    "alias": "READ_PRD",
    "index": "pI1",
    "filter": "-",
    "routing.index": "-",
    "routing.search": "-"
  },
  {
    "alias": "write_PRD",
    "index": "pI1",
    "filter": "-",
    "routing.index": "-",
    "routing.search": "-"
  },
  {
    "alias": ".kibana",
    "index": ".k_1",
    "filter": "-",
    "routing.index": "-",
    "routing.search": "-"
  },
  {
    "alias": "READ_STG",
    "index": "pI2",
    "filter": "-",
    "routing.index": "-",
    "routing.search": "-"
  },
  {
    "alias": "WRITE_STG",
    "index": "pI2",
    "filter": "-",
    "routing.index": "-",
    "routing.search": "-"
  }
]

Upvotes: 0

Views: 1400

Answers (3)

ldz
ldz

Reputation: 2215

Assuming that the JSON is a string called a the following filters by a blacklist

import json
a = """
[]
"""
j = json.loads(a)
blacklist = ['READ_PRD', 'write_PRD', '.kibana']
items = [item for item in j if item['alias'] not in blacklist]
print(items)

Upvotes: 1

oppressionslayer
oppressionslayer

Reputation: 7204

You can accomplish this in pandas like this:

import pandas as pd
df.query("alias not in ['.kibana', 'write_PRD', 'READ_PRD']")[['alias', 'index']].to_dict(orient='records') 

output

[{'alias': 'READ_STG', 'index': 'pI2'}, {'alias': 'WRITE_STG', 'index': 'pI2'}]

Upvotes: 0

C.Nivs
C.Nivs

Reputation: 13106

I would keep your accepted conditions for alias in a set for easy lookup, and then you can do a membership check:

acceptable = {'READ_PRD', 'WRITE_PRD', '.KIBANA'}

for item in x:
    if item.get('alias', '').upper() not in acceptable:
        print(item)

   {
      "alias": "READ_STG",
      "index": "pI2",
      "filter": "-",
      "routing.index": "-",
      "routing.search": "-"
   },
   {
      "alias": "WRITE_STG",
      "index": "pI2",
      "filter": "-",
      "routing.index": "-",
      "routing.search": "-"
   }

The str.upper() call is to account for differences in capitalization

Or, using a filter statement:

list(filter(lambda y: y.get('alias', '').upper() not in acceptable, x))
[
   {
      "alias": "READ_STG",
      "index": "pI2",
      "filter": "-",
      "routing.index": "-",
      "routing.search": "-"
   },
   {
      "alias": "WRITE_STG",
      "index": "pI2",
      "filter": "-",
      "routing.index": "-",
      "routing.search": "-"
   }
]

Upvotes: 1

Related Questions