i got the data from redis with hget.
data = ss.hget("users", "inmove");
the type of data is str.
type(data):
"{u'free_tickets': 2, u'payment_tickets': 1200, u'last': 1420560000, u'user_id': u'inmove'}"
and if i use json.loads(data), the error is
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject
raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)
use ast.literal_eval , your string data is not a json, it is string representation of a python dict.
>>> my_str = "{u'free_tickets': 2, u'payment_tickets': 1200, u'last': 1420560000, u'user_id': u'inmove'}"
>>> from ast import literal_eval
>>> my_dict = literal_eval(my_str)
>>> my_dict.keys()
[u'last', u'user_id', u'free_tickets', u'payment_tickets']
Related
I'm trying to load a dictionary into json but I'm getting error.
strsdc = '''
{"ext":{"amznregion":["useast"],"someURL":"https://som_url.com/x/px/Iyntynt/{"c":"client","als2s":TIME}","id":"7788y"}}
'''
json.loads(strsdc)
gives me the following error:
Traceback (most recent call last):
File "main.py", line 187, in
lol = json.loads(str(strsdc))
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 2 column 79 (char 79)
Your json string is invalid.
I don't know if this is the way you want it but you can try using this string
{"ext":{"amznregion":["useast"],"someURL":"https://som_url.com/x/px/Iyntynt/{\"c\":\"client\",\"als2s\":TIME}","id":"7788y"}}
I am trying to load JSON into a python dict:
>>> d
'[{"amount":"0","categories":["test","test2","test3"],"categoryIds":["A001G001","A003E001A001","A003G002A001","A003T001A001"]}]'
Unfortunatelly I do get an error message which I could not get around:
>>> json.loads(d, strict=False)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 361, in loads
return cls(**kw).decode(s)
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid \escape: line 1 column 410 (char 409)
How can I load the JSON into a python dictionary?
There is an object within the json:
{"amount":"0","categories":["Gereizte Haut","Gesichtspflege f\xFCr allergische Haut","Insektenstiche","Sonnenallergie & Mallorca-Akne","Basispflege & Reinigung"],"categoryIds":["A001G002","HN001A002G001","HN001A002I002","HN001A002S001","HN001N001B001"],"name":"Linola akut 0,5% Creme","price":969,"pzn":"02138990"}
with the string: "Gesichtspflege f\xFCr allergische Haut" which is not valid json.
You need to get your source to encode the data properly.
I'm a newbie into Python and i'm trying to open a json file that looks like this:
{
"empty_char":"",
"empty_number": ,
"char":"i'm a char",
"number":0
}
Let's say that this is the test.json file:
When trying to open it in python I'm using:
import json
with open('test.json') as f:
data = json.load(f)
and it raises the following error:
Traceback (most recent call last):
File "<input>", line 2, in <module>
File "C:\ProgramData\Anaconda3\Lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\ProgramData\Anaconda3\Lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\ProgramData\Anaconda3\Lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\ProgramData\Anaconda3\Lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 19 (char 39)
It gives an error because of "empty_number": ,
How can I deal with this error if I can't modify my .json file?
You can use the more flexible yaml to read in values not provided as None.
import yaml
from io import StringIO
mystr = StringIO("""{
"empty_char":"",
"empty_number": ,
"char":"i'm a char",
"number":0
}""")
# replace mystr with open('test.json', 'r')
with mystr as stream:
res = yaml.load(stream)
print(res, type(res))
{'empty_char': '', 'empty_number': None, 'char': "i'm a char", 'number': 0}
<class 'dict'>
Note io.StringIO lets us read from a string as if it were a file.
After executing the following code:
import json
a = '{"excludeTypes":"*.exe;~\\$*.*"}'
json.loads(a)
I get:
Traceback (most recent call last):
File "", line 1, in
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
So how can I convert 'a' to dict.
Please note that the string is already in 'a' and I cannot add 'r' in front of it. Ideally, the string should have been {"excludeTypes":"*.exe;~\\\\$*.*"}
Also, the following code doesn't work:
import json
a = '{"excludeTypes":"*.exe;~\\$*.*"}'
b = repr(a)
json.loads(b)
import ast
d = ast.literal_eval(a)
By escaping Escape Character "\":
import json
a = '{"excludeTypes":"*.exe;~\\$*.*"}'
a = a.replace("\\","\\\\")
json.loads(a)
I have a json string in a txt file and I'm trying to read it to do some other procedures afterwards. It looks like this:
with open('code test.txt', 'r', encoding=('UTF-8')) as f:
x = json.load(f)
I know the json is valid, but I'm getting:
Traceback (most recent call last):
File "C:\Python33\lib\json\decoder.py", line 368, in raw_decode
obj, end = self.scan_once(s, idx)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module>
user_input()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input
child_remover()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover
x = json.load(f)
File "C:\Python33\lib\json\__init__.py", line 274, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Python33\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:\Python33\lib\json\decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python33\lib\json\decoder.py", line 370, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
I used this website to check if the string is valid. If I use .loads(), I get a different error:
Traceback (most recent call last):
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module>
user_input()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input
child_remover()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover
x = json.loads(f)
File "C:\Python33\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:\Python33\lib\json\decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
Originally the json was embeded in my script like this:
json_text="""json stuff here"""
And didn't get any errors. Any ideas on how to fix this???
Running python 3.3.3 just in case.
Thanks!!
EDIT:
Just some random (valid) json on the txt and I get the same issue. This os one of the ones i tried:
{"data":
{"mobileHelp":
{"value":
{
"ID1":{"children": [1,2,3,4,5]},
"ID2":{"children": []},
"ID3":{"children": [6,7,8,9,10]}
}
}
}
}
Which is valid as well as per jsonlint.com.
Your file contains a UTF-8 BOM character at the start. UTF-8 doesn't need a BOM but especially Microsoft tools insist on adding one anyway.
Open the file with the utf-8-sig encoding instead:
>>> open('/tmp/json.test', 'wb').write(b'\xef\xbb\xbf{"data":\r\n {"mobileHelp":\r\n {"value":\r\n {\r\n "ID1":{"children": [1,2,3,4,5]},\r\n "ID2":{"children": []},\r\n "ID3":{"children": [6,7,8,9,10]}\r\n }\r\n }\r\n }\r\n}')
230
>>> import json
>>> with open('/tmp/json.test', encoding='utf8') as f:
... data = json.load(f)
...
Traceback (most recent call last):
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 367, in raw_decode
obj, end = self.scan_once(s, idx)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 271, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 316, in loads
return _default_decoder.decode(s)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 351, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 369, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>> with open('/tmp/json.test', encoding='utf-8-sig') as f:
... data = json.load(f)
...
>>> data
{'data': {'mobileHelp': {'value': {'ID2': {'children': []}, 'ID3': {'children': [6, 7, 8, 9, 10]}, 'ID1': {'children': [1, 2, 3, 4, 5]}}}}}
Note that from Python 3.4 onwards you get a more helpful error message here:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 314, in loads
raise ValueError("Unexpected UTF-8 BOM (decode using utf-8-sig)")
ValueError: Unexpected UTF-8 BOM (decode using utf-8-sig)
Not sure what your code looks like for the second error, but it looks like you are passing json.loads a file object and not a string. Try:
with open('code test.txt', 'r', encoding=('UTF-8')) as f:
x = json.loads(f.read())
or without newlines with:
with open('code test.txt', 'r', encoding=('UTF-8')) as f:
x = json.loads(f.read().replace('\n', ''))
As another choice, This will be much easier to fix this issue.
json.loads(open('test.txt').read().decode('utf-8-sig'))