0

My JSON file looks something like:

{
    "generator":  {
        "name": "Xfer Records Serum",
    ....
    },
    "generator":  {
        "name: "Lennar Digital Sylenth1",
    ....
    }
}

I ask the user for search term and the input is searched for in the name key only. All matching results are returned. It means if I input 's' only then also both the above ones would be returned. Also please explain me how to return all the object names which are generators. The more simple method the better it will be for me. I use json library. However if another library is required not a problem.

Before switching to JSON I tried XML but it did not work.

rene
  • 41,474
  • 78
  • 114
  • 152
demberto
  • 489
  • 5
  • 15
  • Possible duplicate of [Python json parser allow duplicate keys](https://stackoverflow.com/questions/29321677/python-json-parser-allow-duplicate-keys) – glibdud Jul 29 '19 at 18:44

1 Answers1

0

If your goal is just to search all name properties, this will do the trick:

import re

def search_names(term, lines):
  name_search = re.compile('\s*"name"\s*:\s*"(.*' + term + '.*)",?$', re.I)
  return [x.group(1) for x in [name_search.search(y) for y in lines] if x]

with open('path/to/your.json') as f:
  lines = f.readlines()

print(search_names('s', lines))

which would return both names you listed in your example.

The way the search_names() function works is it builds a regular expression that will match any line starting with "name": " (with varying amount of whitespace) followed by your search term with any other characters around it then terminated with " followed by an optional , and the end of string. Then applies that to each line from the file. Finally it filters out any non-matching lines and returns the value of the name property (the capture group contents) for each match.

JamesT
  • 211
  • 1
  • 5
  • It works! but probably there should be another easier way? use json library instead? – demberto Jul 29 '19 at 20:24
  • json library won't parse the file you've shared a sample of as it isn't a valid JSON file. You can see a similar issue in the post glibdud posted – JamesT Aug 01 '19 at 16:54