0

I am working with twitterAPI collecting tweets for specific keywords. I have already collected all the tweets into a json file. The data looks something like this:

{
    "0": "this is tweet 1",
    "1": "this is tweet 2",
.
.
.
continued
}

Now I want to make a function that loads data from the tweets. So far, I have only been successful this much:

def read_file(jsonfile):

    #reads from my file and saves it in a list called data

    with open(filename, 'r') as fp:
        #i am not sure what to add here to save it as a list

    data = json.loads(content)
    return data

I would be very thankful if anyone could help.

edit: i want my result to be a list named 'xyz'

  • Does this answer your question? [What is the difference between json.dumps and json.load?](https://stackoverflow.com/questions/32911336/what-is-the-difference-between-json-dumps-and-json-load) – sushanth May 20 '20 at 04:17

1 Answers1

1

This should work:

with open(filename, "r") as fp:
    data = json.load(fp)

You want to use json.load() to directly read it from the file. Not json.loads() which reads it from a string, which would require you to unnecessarily first load it from the file into a string.

You can find more details on the json module here.

Glenn Mackintosh
  • 2,765
  • 1
  • 10
  • 18
  • hi, if i were to use json.loads how would the code for that look like? – karan sethi May 20 '20 at 05:00
  • also i wanted the output to be a list* named 'xyz' this returns me a dictionary – karan sethi May 20 '20 at 05:06
  • @karansethi Yes it will be a dict, since that is the structure that you have in the json file you showed. Just like with any dict, you can get a list of values from that dict using the `values()` method on it. In the above case it would be `xyz = data.values()` – Glenn Mackintosh May 20 '20 at 15:55
  • @karansethi I cannot see why you would want to use `json.loads()`. However if you did, `json.loads()` takes a string, so you would have to read the contents of the file into a string and then pass that to it. – Glenn Mackintosh May 20 '20 at 18:23