简体   繁体   中英

How to count occurrences of specific JSON value in python?

I wrote a python script to count number of occurrences of a specific word in JSON but it doesn't count. Here is my JSON file:

[
  {
    "status": "passed",
    "name": "Whiskers",
    "species" : "cat",
    "foods": {
      "likes": ["celery", "strawberries"],
      "dislikes": ["carrots"]
    }
  },
  {
    "status": "failed",
    "name": "Woof",
    "species" : "dog",
    "foods": {
      "likes": ["dog food"],
      "dislikes": ["cat food"]
    }
  },
  {
    "status": "failed",
    "name": "Fluffy",
    "species" : "cat",
    "foods": {
      "likes": ["canned food"],
      "dislikes": ["dry food"]
    }
  }
]

Here is my python script:

import fileinput
import sys
import webbrowser
import json
from collections import Counter

f = open('simplejson2.json')
data = json.load(f)
c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('sta') and v)
print(json.dumps(c)) 
for item in data:
    if str(item['status']) != 'passed':
        c = Counter(k[:] for d in data for k, v in d.items() if k.endswith('led') and v)
        print(json.dumps(c))        
    else:
        print('test case passed sucessfully')

I want to find how many times the "failed" word was used in this JSON script.

Try this one:

import json
f = open('simplejson2.json')
data = json.load(f)
total_len = len(data)
n = 0
count = 0
while n < total_len:
    if data[n]["status"] == "failed":
        count += 1
        
    if n == total_len-1:
        break
    n += 1
    
print("No of failed : %s" % count) 


You are unnecessarily making easy things complex in your code.

Your JSON string is a list of dicts, you could easily iterate over each dict and count.

This code will give you the No. of entries where status is failed .

import json
s = '''[
  {
    "status": "passed",
    "name": "Whiskers",
    "species" : "cat",
    "foods": {
      "likes": ["celery", "strawberries"],
      "dislikes": ["carrots"]
    }
  },
  {
    "status": "failed",
    "name": "Woof",
    "species" : "dog",
    "foods": {
      "likes": ["dog food"],
      "dislikes": ["cat food"]
    }
  },
  {
    "status": "failed",
    "name": "Fluffy",
    "species" : "cat",
    "foods": {
      "likes": ["canned food"],
      "dislikes": ["dry food"]
    }
  }
]'''

d = json.loads(s)
count = 0

for i in d:
    if i['status'] == 'failed':
       count += 1

print(f'Failed: {count}')
Output:

2

There are an easy way is : Using regular expression.
json_string is your string.

import re 
regex = r"failed"
matches = re.findall(regex, json_string, re.MULTILINE)
print(len(matches))
import json
from collections import Counter


data = [
  {
    "status": "passed",
    "name": "Whiskers",
    "species" : "cat",
    "foods": {
      "likes": ["celery", "strawberries"],
      "dislikes": ["carrots"]
    }
  },
  {
    "status": "failed",
    "name": "Woof",
    "species" : "dog",
    "foods": {
      "likes": ["dog food"],
      "dislikes": ["cat food"]
    }
  },
  {
    "status": "failed",
    "name": "Fluffy",
    "species" : "cat",
    "foods": {
      "likes": ["canned food"],
      "dislikes": ["dry food"]
    }
  }
]

c = Counter(v[:] for d in data for k, v in d.items() if v=="failed")
print(json.dumps(c)) 

the output:
{"failed": 2}

Here is the working code for python3. You can do this from the dictionary comprehension step itself. No need for further code.

import json
from collections import Counter

with open('simplejson2.json', 'r') as f:
    str1=f.read()

data=json.loads(str1)

c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed'))
#c now has the count. Below it will check if count is 0 or not and print.
if c['status']>0:
    print("There are",c['status'],"failed cases")
else:
    print("test case passed sucessfully")

You need to familiarize with list and dictionary comprehension to understand this algorithm better.

  1. You don't need all those imports for this code to work: only json and Counter needed. Also, this can be achieved by far less code as others have answered. I'm just posting this for you to easily find the corrections you need in the same code you have.
  2. f.open is discouraged in this age. Start using with open as it will close the file after need.
  3. Remember the python mantra: code should be kept as simple as possible. And if it is necessary, it can be complex but not complicated.

Happy learning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM