我正在使用以下课程轻松存储我的歌曲数据.
class Song:
"""The class to store the details of each song"""
attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')
def __init__(self):
for att in self.attsToStore:
exec 'self.%s=None'%(att.lower()) in locals()
def setDetail(self, key, val):
if key in self.attsToStore:
exec 'self.%s=val'%(key.lower()) in locals()
Run Code Online (Sandbox Code Playgroud)
我觉得这比写出一个if/else
块更具可扩展性.但是,eval
似乎被认为是一种不良做法并且使用起来不安全.如果是这样,任何人都可以向我解释为什么并告诉我一个更好的方法来定义上面的类?
我没有在开始时清楚地解释我的问题.在python中将json转换为字符串时,尝试使用str()和json.dumps().
>>> data = {'jsonKey': 'jsonValue',"title": "hello world"}
>>> print json.dumps(data)
{"jsonKey": "jsonValue", "title": "hello world"}
>>> print str(data)
{'jsonKey': 'jsonValue', 'title': 'hello world'}
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world"}'
>>> str(data)
"{'jsonKey': 'jsonValue', 'title': 'hello world'}"
Run Code Online (Sandbox Code Playgroud)
我的问题是:
>>> data = {'jsonKey': 'jsonValue',"title": "hello world'"}
>>> str(data)
'{\'jsonKey\': \'jsonValue\', \'title\': "hello world\'"}'
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world\'"}'
>>>
Run Code Online (Sandbox Code Playgroud)
我的预期输出:"{'jsonKey':'jsonValue','title':'hello world''}"
>>> data = {'jsonKey': 'jsonValue',"title": "hello world""}
File "<stdin>", line 1
data = {'jsonKey': 'jsonValue',"title": "hello world""} …
Run Code Online (Sandbox Code Playgroud) 我试图将JSON对象解析为Python dict
.我以前从未这样做过.当我搜索这个特定错误时,(第一个char有什么问题?),其他帖子说加载的字符串实际上不是JSON字符串.不过,我很确定这是.
在这种情况下,eval()
工作正常,但我想知道是否有更合适的方式?
注意:此字符串直接来自Twitter,通过ptt工具.
>>> import json
>>> line = '{u\'follow_request_sent\': False, u\'profile_use_background_image\': True,
u\'default_profile_image\': False,
u\'verified\': False, u\'profile_sidebar_fill_color\': u\'DDEEF6\',
u\'profile_text_color\': u\'333333\', u\'listed_count\': 0}'
>>> json.loads(line)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 …
Run Code Online (Sandbox Code Playgroud) 我注意到,单引号引起simplejson
的loads
功能失效:
>>> import simplejson as json
>>> json.loads("\"foo\"")
'foo'
>>> json.loads("\'foo\'")
Traceback (most recent call last):
...
ValueError: No JSON object could be decoded
Run Code Online (Sandbox Code Playgroud)
我正在解析这样的事情:foo = ["a", "b", "c"]
从文本文件到Python中的列表,并且也想接受foo = ['a', 'b', 'c']
.simplejson
方便foo
自动进入列表.
如何loads
在不破坏输入的情况下接受单引号,或自动将双引号替换为单引号?谢谢.
我有一个JSON字符串,如图所示json1
.我试图将其解析为JSON但它似乎无法工作.出了什么问题?
import json
string1 = "[]"
list1 = "['hi','bye']"
json1 = "{'genre': ['Action', 'Comedy']}"
print json.loads(string1)
print json.loads(list1)
print json.loads("{'genre': ['Action', 'Comedy']}")
Run Code Online (Sandbox Code Playgroud)
它给了我错误
Traceback (most recent call last):
File "python", line 8, in <module>
ValueError: No JSON object could be decoded
Run Code Online (Sandbox Code Playgroud) 我正在使用 python 3.9
我收到此错误:
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做时:
import json
print(json.loads("['product', 'font', 'graphics', 'photo caption', 'brand', 'advertising', 'technology', 'text', 'graphic design', 'competition']"))
Run Code Online (Sandbox Code Playgroud)
但当我这样做时它工作得很好:
print(json.loads('["a", "b", "c"]'))
Run Code Online (Sandbox Code Playgroud)
看来错误与引号有关。但请问这是为什么呢?谢谢你!
我有一个嵌套数组作为字符串存储在我的数据库中。获取后,它以字符串形式返回。我需要将它转换回嵌套数组。JSON.parse 对此不起作用,不幸的是,我收到此错误:
VM5481:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 2
本质上,我需要转换这个:
"[['E4', '4n.'], ['D4', '8n'], ['C4', '4n'], ['D4', '4n']]"
Run Code Online (Sandbox Code Playgroud)
对此:
[['E4', '4n.'], ['D4', '8n'], ['C4', '4n'], ['D4', '4n']]
Run Code Online (Sandbox Code Playgroud)
使用 JavaScript。