我这样做是为了阅读文件
f = subprocess.Popen(["../../../abc/def/run_script.sh", "cat", "def/data/ex/details.json"], stdout=subprocess.PIPE)
out = f.stdout.readline()
从上面读取的文件内容如下所示:
{
"def1": {
"val1": 31.6, "val2" : 10
},
"def2": {
"9": {
"val1": 20.1, "val2": 22
}
}
}
我应该怎么做呢。当只有1“val1”和1“val2”时,我用正则表达式进行了简单搜索并保存了值。既然有两个,我需要小心知道我正在处理哪一个..是否有一个简单的出路..?
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 3 (char 2)
答案 0 :(得分:0)
使用the json
module解析JSON。
Python 3代码:
import json
import subprocess
with subprocess.Popen(["cat", "/tmp/foo.json"], stdout=subprocess.PIPE) as f:
j = f.stdout.read()
o = json.loads(j.decode("UTF-8"))
print(o)
print(o["def1"]["val1"])
print(o["def2"]["9"]["val1"])
<强>输出:强>
{'def1': {'val1': 31.6, 'val2': 10}, 'def2': {'9': {'val1': 20.1, 'val2': 22}}}
31.6
20.1
修改强>
对于Python 2,请改用它。
import json
import subprocess
f = subprocess.Popen(["cat", "/tmp/foo.json"], stdout=subprocess.PIPE)
j = f.stdout.read()
o = json.loads(j.decode("UTF-8"))
print o
print o["def1"]["val1"]
print o["def2"]["9"]["val1"]