1

Currently, have multiple JSON files to parse. In each file, I would look for “ID”: “1”:

{“TYPE”: “fire”, “ID”: “1”, “COLOR”: “black”}

and if it is, copy and paste the whole JSON content (which is just 1 line), and paste it onto the result file.

In Python, what would be the right approach to look for a specific key/value in a JSON file to copy to a new file?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jo Ko
  • 7,225
  • 15
  • 62
  • 120
  • 1
    Take a look at [JSON Docs](https://docs.python.org/3/library/json.html) - `import json`, `json.loads()` and then navigate using `json['ID']`, for example. – dot.Py Mar 29 '17 at 17:26
  • @dot.Py do you mind showing as an answer, so I can accept and upvote as well – Jo Ko Mar 29 '17 at 18:14

1 Answers1

2

Step 1 : Load your JSON as a dict

import json
my_json_dict = json.loads(json_string)

The json library parses your JSON string to a Python dictionary.

Step 2 : Access the value using key

value1 = my_json_dict['ID'] 
value1 = my_json_dict.get('ID', default_value) # Preferred.

The first statement will throw an exception if KEY1 is not available in the JSON string. The second statement is safer, as a fallback value can be given.

Step 3 : Apply your business logic

if id == 1:
    # do your operations.

If you must use the first line, or if dealing with unknowns that could throw errors anyway, test for the error you are getting and add exception handling around in it as in:

try:
   <your code solution here>
except NameOfError as ee:
   <what to do if error occurs>
   print(type(ee)); print(ee)    # if you want to see the error 

You can add as many except statements as there are error types you are attempting to process. A generic "Exception" can be used in place of NameOfError as a catch-all for unknown errors, but best practice is to handle the true Exceptions first by type. A little testing as code breaks initially can reveal what should go in place of "NameOfError".

undercovertek
  • 148
  • 1
  • 11
Roopak A Nelliat
  • 2,009
  • 3
  • 19
  • 26
  • Appreciate your response but could you show one with a file, e.g. file1.json? For example, how would I open it and later if it is `id == 1` then copy and paste it to e.g. result.json. – Jo Ko Mar 29 '17 at 18:20