Python在json中获取值

时间:2015-11-19 11:58:34

标签: python json

我需要从key" color"获取值。在json中使用python,仅适用于第一级

json转储:

[{"color": "red", "value": "10"}, {"color": "blue", "value": [{"color": "black", "value": "15"}]}]

我需要:

[ 'red', 'blue']

我试过了:

my_values = my_json_a.get('color')

但有错误:

Error Contents: 'list' object has no attribute 'get'

3 个答案:

答案 0 :(得分:2)

尝试:

data = [{"color": "red", "value": "10"}, {"color": "blue", "value": [{"color": "black", "value": "15"}]}]
results = [x.get('color', None) for x in data]
print results

输出:

['red', 'blue']

答案 1 :(得分:0)

你可以创建一个for循环来遍历你的json字符串,并将每个颜色值附加到一个新列表。

json = [{"color": "red", "value": "10"}, {"color": "blue", "value": [{"color": "black", "value": "15"}]}]
colors =[]
for i in json:
    colors.append(i["color"])
print(colors)

答案 2 :(得分:0)

由于

  BitmapFactory.Options myOptions = new BitmapFactory.Options();
        myOptions.inDither = true;
        myOptions.inScaled = false;
        myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
        myOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.awais, myOptions);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.RED);


        Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
        Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);


        Canvas canvas = new Canvas(mutableBitmap);
        // canvas.drawCircle(60, 50, 25, paint);
        canvas.drawText(String.valueOf(f), h, w, paint);


        imageView.setAdjustViewBounds(true);
        imageView.setImageBitmap(mutableBitmap);

是一个列表,让我们测试一下:

[{"color": "red", "value": "10"}, {"color": "blue", "value": [{"color": "black", "value": "15"}]}]

所以这是一个列表,其中有两个词,所以你需要提取它们。您只需使用列表推导就可以这样做:

>>> my_json_a = [{"color": "red", "value": "10"}, {"color": "blue", "value": [{"color": "black", "value": "15"}]}]

>>> type(my_json_a)
<class 'list'>

>>> for i in my_json_a:
...     print(i)
...     print(type(i))

{'value': '10', 'color': 'red'}
<class 'dict'>
{'value': [{'value': '15', 'color': 'black'}], 'color': 'blue'}
<class 'dict'>