Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

问一个关于python json的问题?

想知道为什么这段代码运行的结果不是想象中的'["123"]'

In [1]: import json

In [2]: t = '[]'

In [3]: t = json.dumps(json.loads(t).append('123'))

In [4]: t
Out[4]: 'null'

但是拆分以后又正常运行?

In [5]: t1 = '[]'

In [6]: t2 = json.loads(t1)

In [7]: t2
Out[7]: []

In [8]: t2.append('123')

In [9]: t2
Out[9]: ['123']

In [10]: t1 = json.dumps(t2)

In [11]: t1
Out[11]: '["123"]'

甚至不引入多一个变量,拆分也是正常运行

In [12]: t1 = '[]'

In [13]: t1 = json.loads(t1)

In [14]: t1
Out[14]: []

In [15]: t1.append('123')

In [16]: t1
Out[16]: ['123']

In [17]: t1 = json.dumps(t1)

In [18]: t1
Out[18]: '["123"]'

请指教


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

列表的append操作返回的是 None, 即 json.loads(t).append('123') 返回的是None

拆开的操作不是 append的返回值,而就是这个列表对象。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...