Simple reading, writing and saving of json files in python

Briefly introduce what json is, the blog here is very detailed https://www.cnblogs.com/SkySoot/archive/2012/04/17/2453010.html

JSON (JavaScript Object Notation) is a lightweight data interchange format. JSON is in a completely language-independent text format, and these features make JSON an ideal data-interchange language. Easy to read and write by humans, but also easy to parse and generate by machines.

In fact, I prefer to attribute json to a dictionary. Take the following submit.json file as an example: the content stored in the following json file

[{"label_id": [0, 11, 12], "image_id": "01dbd060b48994cd8a1aca1f1ebe7cf4febcdeb5.jpg"},

{"label_id": [1, 11, 12], "image_id": "022efb13db1719182cd6868cda18c4da46cae862.jpg"},

{"label_id": [2, 11, 12], "image_id": "03c31c963a11bc8684b4ac6016368365eaa01c30.jpg"},

{"label_id": [3, 11, 12], "image_id": "11389364c084cacc011f6134ac5862735a188fd7.jpg"}]

You can see that there are two words label_id and image_id in this dictionary, let's try to write this json into a txt file

code show as below

  1. import json
  2. json_filename = '/home/hjxu/AI_Challenger-master/code_xu/12.02/submit.json' #This is where the json file is stored
  3. txt_filename = '/home/hjxu/AI_Challenger-master/code_xu/12.02/finnal.txt' #This is where the txt file is saved
  4. file=open(txt_filename,'w')
  5. with open(json_filename) as f:
  6. pop_data = json.load(f)
  7. for pop_dict in pop_data:
  8. label_id = pop_dict['label_id']
  9. image_id = pop_dict['image_id']
  10. temp = str(image_id) + ' ' + str(label_id)
  11. file.write(temp + '\n')
  12. file.close()


This code also mainly uses the json.load() function, which returns a dictionary

Now let's try writing to a json file, again, I prefer to save what needs to be written as a dictionary first, and then write to the json

Writing json mainly uses the json.dump() function,

  1. temp_dict = {}
  2. result = []
  3. submit = './submit.json'
  4. ########## Here you can write a loop to join the dictionary ########
  5. temp_dict[ 'num' ] = len (os.listdir(a)) #Statistics
  6. temp_dict[ 'classification' ] = num_name #category
  7. temp_dict[ 'prob' ] = num_name_prob #probability
  8. result.append(temp_dict)
  9. #################################################################################################################################################################3
  10. with open(submit, 'w') as f:
  11.     json.dump(result, f)


Related: Simple reading, writing and saving of json files in python