簡體   English   中英

如何提取嵌套的 json object 值 Python

[英]How to extract nested json object values Python

有人可以幫助提取嵌套的 json 值。 我有一個 json 結構。 我只想從嵌套的 json 中獲取值,不包括密鑰。 我們是否有任何預定義的函數可以使用

{
 '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
  }
}
 ]
}

我想要這種格式的 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
}
 ]
 }

有沒有辦法只從嵌套的 json 中提取值。 我希望從我的 output 中刪除“類型”,並為現有的 object 添加價值

我假設你得到了一個字典/列表結構而不是一個 json 字符串(如果是后者,使用json.loads )。 那么你的問題基本上是

我如何轉換

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

進入

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

一種方法是

d.update(d.pop(key_2))

有關dict.updatedict.pop的解釋,請參閱dict的文檔 :)

現在對於您的用例,您只需對'category'列表中的每個字典重復該操作,可能使用for循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM