Home > front end >  JSON processing using Python and downloading datas by parameters
JSON processing using Python and downloading datas by parameters

Time:01-17

I am Python newbie and I want to ask for your help. So I have a JSON file which looks like this:

{
    "1": {
        "name": "Test1",
        "url": "https://example.com/NoPic.png",
        "notdefault": false
    },
    "2": {
        "name": "Test2",
        "url": "https://example.com/pic2.png",
        "notdefault": true
    },
    "3": {
        "name": "Test3",
        "url": "https://example.com/NoPic.png",
        "notdefault": false
    },
....
}

I want to read the datas.json file in Python and download every images from "url" parameter where the "notdefault" parameter is true. I tried many .json file reading methods in Python but I can't figure it out how to do that.

CodePudding user response:

You will find the json module very helpful. Here's one way to do it:

import json
with open('a.json') as j:
    for v in json.load(j).values():
        print(v['url'])

CodePudding user response:

Combination of those 2 codes I printed out every urls where the notdefault is true.

import json
import requests

with open('coospace.json', encoding="utf8") as j:
    for n, element in json.load(j).items():
        if element["notdefault"]:
            print(element['url'])

Thanks for helping!

CodePudding user response:

You could follow an approach like this:

import requests
import json

json_obj = json.loads(json_str) # json_str is your json

for n, element in json_obj.items():
    if element["notdefault"]:
        img = requests.get(element["url"]).content
        with open(element["name"]) as output:
            output.write(img)


Just to be clear: this reads the document and downloads the images in the links as described in the original question. I don't think that simply printing the links answer the question completely.

  •  Tags:  
  • Related