Python JSON dump accended characters - json

I'm using a program called Wrapper.py(this), but there's some type of error. Becouse it's Python, I've tried to found the error. As far as I know, the error is at that it tries to write & load some JSON, but it receives strings like this: "Közép-európai nyelvezet", or something like this. It causes UnicodeDecodeError:
>>>import json
>>>out={"a":"Közép-európai nyelvterület"}
>>>json.dumps(out)
Tracebank(the path, etc.)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 1: Invalid start byte
Then I googled, & found that solution for encoding:
>>>a=json.dumps(out,ensure_ascii=False)
>>>a
'{"a":"K\x94z\x82p-eur\xarpai nyelvter\x81let"}'
Then I wanted to load it:
>>>json.loads(a)
Traceback, etc.
UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 1: Invalid start byte
>>>json.load(a,ensure_ascii=False)
Traceback
TypeError: __init__() got an unespected keyword argument: 'ensure_ascii'
How can I load my data back?
Thanks in advance for your help!

Use text instead of bytestrings.
out = {u"a":u"Közép-európai nyelvterület"}

Related

How can a read csv.deflate hdfs files in a dask datfarame?

I am trying to read csv.deflate files from hdfs path and put them in dask dataframe. I tried read_csv and I am getting "UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9c in position 1: invalid start byte" error. Then, I set engine='python' and encoding='utf-8' but I am still getting the same error.
Perhaps the compression= keyword would help? How would you read this data locally with Pandas? I suspect that you need the same keyword arguments that you would need in that case.

Error while reading JSON file with Python

I am getting an error while reading JSON file using python's json module and I'm not able to understand what is wrong. Below are my files and code for your reference:
json.load(files_lst[1])
error:
AttributeError: 'str' object has no attribute 'read'
After reading several answers I also tried:
json.loads(files_lst[1])
but I get the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
What is wrong here? Thanks a lot for your help
>>> files_lst
['All_Transcripts/x3021_10.50.48.111_04-04-2019.json',
'All_Transcripts/x5363_09.33.36.955_08-27-2019.mp3.json',
'All_Transcripts/x3580_11.35.53.462_05-13-2019.json',
'All_Transcripts/x4342_08.55.01.523_08-01-2019.json',
'All_Transcripts/x9496_15.26.32.382_05-21-2019.json',
'All_Transcripts/x5374_08.38.15.692_06-17-2019.json',
'All_Transcripts/x4342_13.43.57.128_03-21-2019.json']
json.load accepts an open file descriptor. So you should call it like this:
json.load(open(files_lst[1]))
json.loads accepts a json as a string. So you should call it like this:
json.loads(open(files_lst[1]).read())

PYTHON3: How to print a byte string with unicode character to console? and use in json.load(..)?

i have a Post Service function and when i do:
json_data = json.loads(request.data)
i have this error:
'ascii' codec can't encode characters in position 19-20: ordinal not in range(128)
the json that i send is this with COMPARTIMENT="à" if i do:
print(str(request.data))=>
b'[{"COMPARTIMENT":"\xc3\xa0","TYPE":"AN1/2018"}]\n'
i want first print my json with COMPARTIMENT="à" on console and not \xc3\xa0.
After i want use json.loads(request.data) without error.
Some tips for me?
thanks
Regards

UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

I am trying to read twitter data from json file using python 2.7.12.
Code I used is such:
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def get_tweets_from_file(file_name):
tweets = []
with open(file_name, 'rw') as twitter_file:
for line in twitter_file:
if line != '\r\n':
line = line.encode('ascii', 'ignore')
tweet = json.loads(line)
if u'info' not in tweet.keys():
tweets.append(tweet)
return tweets
Result I got:
Traceback (most recent call last):
File "twitter_project.py", line 100, in <module>
main()
File "twitter_project.py", line 95, in main
tweets = get_tweets_from_dir(src_dir, dest_dir)
File "twitter_project.py", line 59, in get_tweets_from_dir
new_tweets = get_tweets_from_file(file_name)
File "twitter_project.py", line 71, in get_tweets_from_file
line = line.encode('ascii', 'ignore')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte
I went through all the answers from similar issues and came up with this code and it worked last time. I have no clue why it isn't working now.
In my case(mac os), there was .DS_store file in my data folder which was a hidden and auto generated file and it caused the issue. I was able to fix the problem after removing it.
It doesn't help that you have sys.setdefaultencoding('utf-8'), which is confusing things further - It's a nasty hack and you need to remove it from your code.
See https://stackoverflow.com/a/34378962/1554386 for more information
The error is happening because line is a string and you're calling encode(). encode() only makes sense if the string is a Unicode, so Python tries to convert it Unicode first using the default encoding, which in your case is UTF-8, but should be ASCII. Either way, 0x80 is not valid ASCII or UTF-8 so fails.
0x80 is valid in some characters sets. In windows-1252/cp1252 it's €.
The trick here is to understand the encoding of your data all the way through your code. At the moment, you're leaving too much up to chance. Unicode String types are a handy Python feature that allows you to decode encoded Strings and forget about the encoding until you need to write or transmit the data.
Use the io module to open the file in text mode and decode the file as it goes - no more .decode()! You need to make sure the encoding of your incoming data is consistent. You can either re-encode it externally or change the encoding in your script. Here's I've set the encoding to windows-1252.
with io.open(file_name, 'r', encoding='windows-1252') as twitter_file:
for line in twitter_file:
# line is now a <type 'unicode'>
tweet = json.loads(line)
The io module also provide Universal Newlines. This means \r\n are detected as newlines, so you don't have to watch for them.
For others who come across this question due to the error message, I ran into this error trying to open a pickle file when I opened the file in text mode instead of binary mode.
This was the original code:
import pickle as pkl
with open(pkl_path, 'r') as f:
obj = pkl.load(f)
And this fixed the error:
import pickle as pkl
with open(pkl_path, 'rb') as f:
obj = pkl.load(f)
I got a similar error by accidentally trying to read a parquet file as a csv
pd.read_csv(file.parquet)
pd.read_parquet(file.parquet)
The error occurs when you are trying to read a tweet containing sentence like
"#Mike http:\www.google.com \A8&^)((&() how are&^%()( you ". Which cannot be read as a String instead you are suppose to read it as raw String .
but Converting to raw String Still gives error so i better i suggest you to
read a json file something like this:
import codecs
import json
with codecs.open('tweetfile','rU','utf-8') as f:
for line in f:
data=json.loads(line)
print data["tweet"]
keys.append(data["id"])
fulldata.append(data["tweet"])
which will get you the data load from json file .
You can also write it to a csv using Pandas.
import pandas as pd
output = pd.DataFrame( data={ "tweet":fulldata,"id":keys} )
output.to_csv( "tweets.csv", index=False, quoting=1 )
Then read from csv to avoid the encoding and decoding problem
hope this will help you solving you problem.
Midhun

Error converting string to dictionary object

I am converting the Json string into a Python dictionary object and I get the following error for the below code:
import json
path = 'data2012-03-16.txt'
records = [json.loads(line) for line in open(path)]
Error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 6: invalid start byte
few suggestion-
Maybe the encoding of the file is not valid? try to open it in notepad++ and change the encoding.
Are you sure your json file is well formatted? try open it in json parser and check it.
Why you got error with byte 0x92 in position 6 what is in this index of your file? maybe you have problem with all the \/ issue, try to replace it with other letters and check if it is working. beside, you can use the elimination way and try to open other file with the same code.After that work open thin version of this file etc.