简体   繁体   English

在Python中使用json.load时,JSON文件转换为字符串

[英]JSON file is converted to string while using json.load in Python

I have a valid JSON file but when i am using json.load(), it gets converted to string instead of Python dictionary. 我有一个有效的JSON文件,但是当我使用json.load()时,它会转换为字符串而不是Python字典。

My JSON string: 我的JSON字符串:

{
  "colors": [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]
}

It is named as color.json 它被命名为color.json

My Python code is: 我的Python代码是:

import json
with open("color.json") as f:
    data=json.load(f)
print(type(data))

It shows output as class 'str'. 它将输出显示为类“ str”。 why is it not being converted to dictionary? 为什么不将其转换为字典?

I have extended your code as below with your provided json file 我已使用您提供的json文件扩展了您的代码,如下所示

import json
with open("color.json") as f:
    data=json.load(f)
print(type(data))

listofkeys=[keys for keys in data.keys()]
print(listofkeys)

color_keys=[keys2 for keys2 in data["colors"][0].keys()]
print(color_keys)

And Output is as below 和输出如下

<class 'dict'>
['colors']
['category', 'color', 'code', 'type']

First thing is it is returning dict type only. 第一件事是它仅返回dict类型。 And it is having only one key colors as we have printed out. 正如我们已经打印出的那样,它只有一种主要colors

And Second thing is this colors key is having list of dictionaries as its value which are as well printed in our code. 第二件事是此颜色键具有在其代码中也已打印的字典列表作为其值。 category color code type are four dictionaries category color code type是四个字典

And you can further explore these dictionaries. 您可以进一步探索这些词典。

and the above mentioned code is working in both python2 and 3 versions. 并且上述代码在python2和3版本中均适用。 Check again. 再检查一遍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM