我有一个对象的json数组,如下所示:
{
"testcases": {
"testcase": {
"custom-fields": {
"custom-field": [{
"@id": "testCaseID",
"@content": "shotwell15"
}, {
"#text": "-",
"@id": "casecomponent"
}, {
"#text": "critical",
"@id": "caseimportance"
}]
},
"title": "Shotwell 15"
}
}
}
我正在尝试使用python并根据custom-field
的“值”从@id
数组中获取对象,如下所示:
找到对象:
{
"#text": "critical",
"@id": "caseimportance"
}
基于“案例重要性”值
我尝试使用过滤器,但这似乎不起作用。我认为应该不难。用javascript或ruby做的事情很简单。在红宝石中,我可以使用.select方法
答案 0 :(得分:1)
python模块're'具有搜索功能,您可以查看该功能,该功能可以过滤出特定的单词,然后使用索引来选择该单词周围的其他单词/ json文件的文本。
答案 1 :(得分:1)
在Python中,您可以使用list comprehension类似于Ruby的select:
import...
public class Calentando extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN );
setContentView( R.layout.activity_calentando );
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private byte[] readFile(String path) {
File file = new File( "/sys/class/gpio/gpio33/value" );
try (FileInputStream fis = new FileInputStream( file );
BufferedInputStream bis = new BufferedInputStream( fis )) {
byte[] buffer = new byte[4096];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((bytesRead = bis.read( buffer )) != -1) {
baos.write( buffer, 0, bytesRead );
TextView Tempview = (TextView) findViewById( R.id.temperatura );
Tempview.setText( new String( readFile( path ), Charset.forName( "UTF-8" ) ) );
}
return baos.toByteArray();
} catch (IOException e) {
// handle the exception
return null;
}
}
}
Python还有一个过滤器,可以更直接地与Ruby的select进行比较:
Python 2:
custom_fields = data["testcases"]["testcase"]["custom-fields"]["custom-field"]
filtered = [f for f in custom_fields if f["@id"] == "caseimportance"]
Python 3:
filtered = filter(lambda f: (f["@id"] == "caseimportance"), custom_fields)
列表理解通常被认为是更Python化的。