1

Invalid Argument error while reading external json file's values in python

I tried:

import json

with open('https://www.w3schools.com/js/json_demo.txt') as json_file:
    data = json.load(json_file)
    #for p in data['people']:
    print('Name: ' + data['name'])

Gave me error:

with open('https://www.w3schools.com/js/json_demo.txt') as json_file: OSError: [Errno 22] Invalid argument: 'https://www.w3schools.com/js/json_demo.txt'

Grass
  • 185
  • 2
  • 14
  • 3
    `open` is for opening local files, not URLs. – jonrsharpe Sep 10 '18 at 17:13
  • @jonrsharpe then what to use? – Grass Sep 10 '18 at 17:15
  • 4
    https://stackoverflow.com/questions/1393324/in-python-given-a-url-to-a-text-file-what-is-the-simplest-way-to-read-the-cont – fl00r Sep 10 '18 at 17:15
  • If you want to stick to the standard library, see https://docs.python.org/3/library/internet.html. – jonrsharpe Sep 10 '18 at 17:16
  • Can anyone please help me with: 1) [Chrome opens with “Data;” with selenium chromedriver](https://stackoverflow.com/questions/52243080/chrome-opens-with-data-with-selenium-chromedriver) and 2) [Console Log/ cmd.exe not closing in chromedriver](https://stackoverflow.com/questions/52236941/console-log-cmd-exe-not-closing-in-chromedriver) – Grass Sep 10 '18 at 17:46

2 Answers2

2

Use requests

import requests
response = requests.get('https://www.w3schools.com/js/json_demo.txt')
response.encoding = "utf-8-sig"
data = response.json()
print(data['name'])
>>> John
degenTy
  • 340
  • 1
  • 9
2

As open is for opening local files, not URLs as commented by jonrsharpe so, go with urllib as commented by fl00r.

Though the link provided by him was for python-2

Try this (python-3):

import json
from urllib.request import urlopen

with urlopen('https://www.w3schools.com/js/json_demo.txt') as json_file:
    data = json.load(json_file)
    #for p in data['people']:
    print('Name: ' + data['name'])

John

Chirag Jain
  • 1,367
  • 1
  • 11
  • 27