Home > database >  My script is reading my JSON file as empty when it's not?
My script is reading my JSON file as empty when it's not?

Time:11-16

Here is my config file:

{
"credentials":
  {
    "server": "0.1.2.3,6666",
    "database": "db", 
    "username": "user",
    "password": "password"
  }
}

Here is my python script in a separate file:

import pandas as pd
import datatest as dt
import datetime 
import json
import pyodbc

with open(r"path_to_config.json", 'r') as config_file:
    lines=config_file.readlines()
    df = json.load(config_file)

server=config_file['server']
database=config_file['database']
username=config_file['username']
password=config_file['password']

connection_string = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
                                   'SERVER=' server ';'
                                   'DATABASE=' database ';'
                                   'UID=' username ';'
                                   'PWD=' password ';')
cursor = connection_string.cursor()

SQL_STATEMENT = "SELECT COUNT(*) FROM table1"
cursor.execute(SQL_STATEMENT)

for i in cursor:
    print(i)

Here is my error:

    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I've tried using json.loads(), I have tried creating a dictionary in my json file, I'm using readlines() and I've tried read() as well, I'm not sure what to do. My JSON file has data in it, not sure why the error is saying it expects data because it's right there. I think the issue lies where I am defining: server=config_file['server']

CodePudding user response:

Once you've read run readlines, the stream has finished and is now empty!
If you need the lines for something, then you should load the json separately, for instance (without indentation):

df = json.load(open(r"path_to_config.json", 'r'))  # No indentation, outside the "with"

and if you don't need the lines variable, then don't run that line at all:

with open(r"path_to_config.json", 'r') as config_file:
    df = json.load(config_file)

CodePudding user response:

When you use config_file.readlines() you reach the end of the file, so json.load(config_file) has nothing to read.

You can add config_file.seek(0) before json.load(config_file) to get to the beginning of the file, or even better, just remove lines = config_file.readlines().

CodePudding user response:

When you use config_file.readlines() it moves the "cursor" to the end of the file and thus there's nothing more to read when you call json.load(). You can either open the file again or just remove the config_file.readlines() call since its results are unused.

  • Related