2017-10-13 2 views
-1

Ich habe folgende JSON-Datei:Bash-Skript filtern JSON Text

{ 
    "error": 0, 
    "data": { 
    "0": { 
     "orderid": "40007600", 
     "price": "9.99", 
     "listingname": "iPhone 8", 
     "smallphoto": "https://images-eu.ssl-images-amazon.com/images/I/51b5iaLTjgL._SL160_.jpg", 
     "photo": "https://images-eu.ssl-images-amazon.com/images/I/51b5iaLTjgL.jpg" 
    }, 
    "1": { 
     "orderid": "40007598", 
     "price": "9.99", 
     "listingname": "iPhone 8 Plus", 
     "smallphoto": "https://images-eu.ssl-images-amazon.com/images/I/51CVLqsSNkL._SL160_.jpg", 
     "photo": "https://images-eu.ssl-images-amazon.com/images/I/51CVLqsSNkL.jpg" 
    }, 
    "4": { 
     "orderid": "40007595", 
     "price": "9.39", 
     "listingname": "Nadelflaschen", 
     "smallphoto": "https://images-eu.ssl-images-amazon.com/images/I/41OHDP2rAeL._SL160_.jpg", 
     "photo": "https://images-eu.ssl-images-amazon.com/images/I/41OHDP2rAeL.jpg" 
    }, 
    } 
} 

Wie kann ich alles mit einem Bash-Skript filtern, so dass ich all Bild-URLs von „smallphoto“ in eine Textdatei?

f.e. https://images-eu.ssl-images-amazon.com/images/I/41OHDP2rAeL.SL160.jpg von "Nadelflachen"

Ich habe versucht awk und jq Befehle. Aber ich bin nur um zu dumpen, um die jq-Syntax zu verstehen.

awk ist möglich, aber ich bekomme nur ungefilterte Links mit Backslashes, die nicht funktionieren.

+0

Willkommen bei Stackoverflow. Leider ist dies weder eine Tutorialseite noch ein Ersatz für die Websuche. Wir können helfen, [bestimmte Probleme] zu lösen (https://stackoverflow.com/help/on-topic), aber es ist ** dein ** Job, [einige Anstrengungen zu machen] (http://meta.stackoverflow.com/questions/261592) an erster Stelle, inkl. elementary [(re) search] (https://google.com/). Die Mehrheit der Fragen von Neueinsteigern ist nicht einzigartig und wurde bereits mehrfach beantwortet. –

Antwort

3
jq '.data[] | .smallphoto' input.json 

Ausbeuten:

"https://images-eu.ssl-images-amazon.com/images/I/51b5iaLTjgL._SL160_.jpg" 
"https://images-eu.ssl-images-amazon.com/images/I/51CVLqsSNkL._SL160_.jpg" 
"https://images-eu.ssl-images-amazon.com/images/I/41OHDP2rAeL._SL160_.jpg" 

Die hier entscheidende Punkt ist, dass .[] (.data[] eine abgekürzte Form von .data|.[] ist) kann mit JSON Objekten verwendet werden, nicht nur Arrays.

1

ist hier ein anderer Filter, der .smallphoto egal wie tief verschachtelten finden:

.. | .smallphoto?//empty 

Try it online!

Sample Run (annimmt korrigierte Beispieldaten in data.json)

$ jq -M '.. | .smallphoto?//empty' data.json 
"https://images-eu.ssl-images-amazon.com/images/I/51b5iaLTjgL._SL160_.jpg" 
"https://images-eu.ssl-images-amazon.com/images/I/51CVLqsSNkL._SL160_.jpg" 
"https://images-eu.ssl-images-amazon.com/images/I/41OHDP2rAeL._SL160_.jpg"