简体   繁体   English

如何提取嵌套的 json object 值 Python

[英]How to extract nested json object values Python

Can someone please help to extract the nested json values.有人可以帮助提取嵌套的 json 值。 I have a json structure.我有一个 json 结构。 I want to get only value from nested json excluding the key.我只想从嵌套的 json 中获取值,不包括密钥。 Do we have any predefined funtcions to use我们是否有任何预定义的函数可以使用

{
 'catalog': [
{
  'catalog_num': 120,
  'type': {
    'screen_inch': 18.0,
    'screen_width': 240.0,
    'screen_height': 78.0
  }
},
{
  'catalog_num': 9992,
  'type': {
    'screen_inch': 18.0,
    'screen_width': 36.0,
    'screen_height': 78.0
  }
},
{
  'catalog_num': 100,
  'type': {
    'screen_inch': 24.0,
    'screen_width': 576.0,
    'screen_height': 78.0
  }
}
 ]
}

I want the output in this format:-我想要这种格式的 output:-

{
  'catalog': [
{
  'catalog_num': 120,
    'screen_inch': 18.0,
    'screen_width': 240.0,
    'screen_height': 78.0
},
{
  'catalog_num': 9992,
    'screen_inch': 18.0,
    'screen_width': 36.0,
    'screen_height': 78.0
},
{
  'catalog_num': 100,
    'screen_inch': 24.0,
    'screen_width': 576.0,
    'screen_height': 78.0
}
 ]
 }

Is there any way to extract only values from nested json.有没有办法只从嵌套的 json 中提取值。 I want the "type" to get removed from my output and add value to existing object我希望从我的 output 中删除“类型”,并为现有的 object 添加价值

I'll assume that you're given a dictionary/list structure instead of a json-string (if it's the latter, use json.loads ).我假设你得到了一个字典/列表结构而不是一个 json 字符串(如果是后者,使用json.loads )。 Then your question basically is那么你的问题基本上是

How do I convert我如何转换

d = { key_1: value_1, key_2: {key_3: value_3} }

into进入

d = { key_1: value_1, key_3: value_3 } ? d = { key_1: value_1, key_3: value_3 } ?

One way to do that would be一种方法是

d.update(d.pop(key_2))

Please see the docs of dict for an explanation of dict.update and dict.pop :)有关dict.updatedict.pop的解释,请参阅dict的文档 :)

Now for your use case, you'll just need to repeat that for each of the dictiories in the 'category' list, probably with a for loop.现在对于您的用例,您只需对'category'列表中的每个字典重复该操作,可能使用for循环。

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

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