Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read json object in python [duplicate]

i have json file named "panamaleaks50k.json" . I want to get ['text'] field from json file but it shows me following error

the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'

this is my code

with open('C:/Users/bilal butt/Desktop/PanamalEakJson.json','r') as lst:     b = json.loads(lst)     print(b['text']) 

my json file look

[ {    "fullname": "Mohammad Fayyaz",    "id": "885800668862263296",    "likes": "0",    "replies": "0",    "retweets": "0",    "text": "Love of NS has been shown in PanamaLeaks scandal verified by JIT...",    "timestamp": "2017-07-14T09:58:31",    "url": "/mohammadfayyaz/status/885800668862263296",    "user": "mohammadfayyaz"  }, {   "fullname": "TeamPakistanPTI \u00ae",   "id": "885800910357749761",   "likes": "0",   "replies": "0",   "retweets": "0",   "text": "RT ArsalanISF: #PanamaLeaks is just a start. U won't believe whr...",   "timestamp": "2017-07-14T09:59:29",   "url": "/PtiTeampakistan/status/885800910357749761",   "user": "PtiTeampakistan"  } ] 

how i can read all ['text'] and just single ['text'] field?

like image 413
Bilal Butt Avatar asked Dec 17 '17 16:12

Bilal Butt


People also ask

How do I remove duplicates from a list in JSON Python?

The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given. The combination of list comprehension and enumerate is used to remove the duplicate elements from the list.

Can JSON have duplicate keys Python?

python - json. loads allows duplicate keys in a dictionary, overwriting the first value - Stack Overflow.

Can JSON have duplicate fields?

We can have duplicate keys in a JSON object, and it would still be valid.


2 Answers

You should pass the file contents (i.e. a string) to json.loads(), not the file object itself. Try this:

with open(file_path) as f:     data = json.loads(f.read())     print(data[0]['text']) 

There's also the json.load() function which accepts a file object and does the f.read() part for you under the hood.

like image 64
Eugene Yarmash Avatar answered Sep 30 '22 13:09

Eugene Yarmash


Use json.load(), not json.loads(), if your input is a file-like object (such as a TextIOWrapper).

Given the following complete reproducer:

import json, tempfile with tempfile.NamedTemporaryFile() as f:     f.write(b'{"text": "success"}'); f.flush()     with open(f.name,'r') as lst:         b = json.load(lst)         print(b['text']) 

...the output is success.

like image 21
2 revs Avatar answered Sep 30 '22 14:09

2 revs