0

I have made this program which should log in a JSON file if my network loses connection to the outside world.(My Dsl connection is pretty unstable.) But have difficulties getting json.loads() to accept my data-object.

I have tried to cast it as a str but it still throws errors.

TypeError: the JSON object must be str, bytes or bytearray, not dict

CODE:

#!/usr/bin/python3
import platform    # For getting the operating system name
import subprocess  # For executing a shell command
import json
import time

router = "192.168.178.1"
web_ip_address = "1.1.1.1"

def ping(web_ip_address):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """
    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', '-q', web_ip_address]

    return subprocess.call(command) == 0

response = ping(web_ip_address)
localresponse = ping(router)

data = {
    "router_online": localresponse,
    "ip_address": web_ip_address,
    "timestamp": time.ctime()
}

if response == True:
  print((web_ip_address), 'is reachable!')
else:
  print((web_ip_address), 'is unreachable!') #writes the data only if the internet connection is down
  obj = json.loads(data)

  with open('Downtime_Data.json', 'a') as json_file:
    json.dump(obj, json_file, indent = 2 , sort_keys = True,)
1
  • You're going from a dict to a JSON string, not vice-versa, so you want json.dump() rather than json.loads(). Commented Jul 3, 2021 at 15:38

1 Answer 1

1

JSON is a string format, that can be loaded into objects depending on the language, in python that dict, list for the containers

d = {"key": "value"}  # d is a dict object
s = json.dumps(d)     # s is a string
d = json.loads(s)

Your data is a python object, a dict, there is no json.loads to call. Just dump

if response:
    print(web_ip_address, 'is reachable!')
else:
    data = {"router_online": localresponse, "ip_address": web_ip_address, "timestamp": time.ctime()}
    print(web_ip_address, 'is unreachable!')
    with open('Downtime_Data.json', 'a') as json_file:
        json.dump(data, json_file, indent=2, sort_keys=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.