Skip to content
Advertisement

How to display accented words JSON on bash script with Python

I’m trying to display arrays with accent in the result but only arrays that don’t have accent are showing.

Complete themoviedb API: https://api.themoviedb.org/3/movie/566525?api_key=b2f8880475c888056b6207067fbaa197&language=pt-BR

  "genres": [
    {
      "id": 28,
      "name": "Ação"
    },
    {
      "id": 12,
      "name": "Aventura"
    },
    {
      "id": 14,
      "name": "Fantasia"
    }
  ],

  "overview": "Shang-Chi precisa confrontar o passado que pensou ter deixado para trás. Ao mesmo tempo, ele é envolvido em uma teia de mistérios da organização conhecida como Dez Anéis.",


Shell code:

getMovieInfo()
{

  movieInfo=$(httpGet "https://api.themoviedb.org/3/movie/566525?api_key=b2f8880475c888056b6207067fbaa197&append_to_response=videos&language=pt-BR")
  genreOne=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][0]['name']" 2> /dev/null )
  genreTwo=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][1]['name']" 2> /dev/null )
  genreThree=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][2]['name']" 2> /dev/null )
  genres=$(echo "$genreOne $genreTwo $genreThree" | tr " " ",")
  overview=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['overview']" 2> /dev/null )
}

result:

==========================================
| Title: Shang-Chi and the Legend of the Ten Rings
| Language: en
| Genre: ,Aventura,Fantasia
| Runtime: 132 mins
| Overview:
==========================================

Advertisement

Answer

Here is a cleaner way to do this in jq. This solution also scales better (you don’t need to know the number of elements in your array)

my_function() {
  movieInfo="$(httpGet "https://api.themoviedb.org/3/movie/566525?api_key=b2f8880475c888056b6207067fbaa197&append_to_response=videos&language=pt-BR")"
  language="$(jq -r '.original_language' <<< $movieInfo)"
  genres="$(jq -r '[.genres[].name] | join(",")' <<< $movieInfo)"
  runtime="$(jq -r '.runtime' <<< $movieInfo)"
  overview="$(jq -r '.overview' <<< $movieInfo)"
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement