-1

I am trying to convert a json file to txt:

def json_to_plaintext(json_file):

    json_tmp = json.loads(json_file.read())
    attr = str(json_tmp["meta"])  # collect attribute
    txt_file = open("json_attr.txt", "w+")
    attr = str(attr)  # make string of object
    txt_file.write(attr)
    txt_file.close()
    json_file.close()

    return txt_file

When I call json_to_plaintext("json_file") I get: AttributeError: 'str' object has no attribute 'read'. json_file is a correct json file, so that should not be an issue. As goes for my code, my understanding is that it should work since I do json.loads(json_file.read()), which often can be an issue otherwise.

Is the function perceiving the parameter "json_file" as a string instead of a file-object? If so, how should I pass my json-file as a parameter? If not, what may cause this error?

zkalman
  • 17
  • 6

2 Answers2

0

It seems that you do not open the file before passing it to your function. This can be done within the function itself:

import json      

def json_to_plaintext(json_file):

    with open(json_file, 'r') as myfile:
        json_tmp = json.load(myfile)
    ...
Fourier
  • 2,795
  • 3
  • 25
  • 39
  • This was the issue. When I open the file in the terminal and then pass it, it works. But when I try to open it in the function I get the error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0), any idea why this won't work? – zkalman Nov 15 '19 at 10:29
  • Please try my updated answer. Are there any symbols in there, that the decoder might not be able to handle? How do you pass the file? – Fourier Nov 15 '19 at 10:35
  • Just regular letters. I pass it from the console by: json_to_plaintext("json_file") – zkalman Nov 15 '19 at 10:40
0

This may help you:

import json
def json_to_plaintext(json_file):

    with open(json_file, 'r') as myfile:
        json_tmp = json.loads(myfile.read())
        attr = str(json_tmp["amazon"])  # collect attribute
        txt_file = open("json_attr.txt", "w+")
        attr = str(attr)  # make string of object
        txt_file.write(attr)
        txt_file.close()


    return txt_file


if __name__=="__main__":
    a=json_to_plaintext("configuration_file")
    print(a)
Puja Neve
  • 50
  • 7