简体   繁体   English

更新python中的Json值

[英]Update Json value in python

I am trying to specify a name for my google spreadsheet api. 我正在尝试为我的Google电子表格api指定一个名称。 This is done in the 'title' key value. 这是在“标题”键值中完成的。 I have tried with the below but it adds a new key to the existing json. 我在下面尝试过,但是它向现有的json添加了新密钥。 Is there a way to get to the "title": "" and update that value with the new_date item? 有没有一种方法可以到达"title": ""并使用new_date项目更新该值?

prev_date =  datetime.date.today()-datetime.timedelta(1)
new_date = str(prev_date.isoformat())
res = {
  "requests": [
    {
      "addSheet": {
        "properties": {
          "title": ""
        }
      }
    }
  ]
}
res['title'] =  new_date
print (res)

This is the output: 这是输出:

{'requests': [{'addSheet': {'properties': {'title': ''}}}], 'title': '2016-12-29'}

This is what I would like it to be: 这就是我想要的:

{'requests': [{'addSheet': {'properties': {'title': '2016-12-29'}}}]}

From the structure you mentioned, the title key that you need to modify is more nested than what you are providing with. 从您提到的结构中,您需要修改的title密钥比提供的title嵌套的更多。

You need to make the following change: 您需要进行以下更改:

prev_date =  datetime.date.today()-datetime.timedelta(1)
new_date = str(prev_date.isoformat())
res = {
  "requests": [
    {
      "addSheet": {
        "properties": {
          "title": ""
        }
      }
    }
  ]
}
res['requests'][0]['addSheet']['properties']['title'] =  new_date
print (res)

Where: 哪里:

  • 'requests' value is a list 'requests'值是一个list
  • 0 is the first item in the list (and the only item) 0是列表中的第一项(也是唯一项)
  • 'addSheet' is the key in the dictionary that is the value of the item in the list in the 0 index 'addSheet'是字典中的键,它是0索引中列表中项目的值
  • 'properties' is the key in the above dictionary 'properties'是以上字典中的键
  • 'title' is the key in the above dictonary, and the one you need upon your request 'title'是以上字典中的关键,也是您根据要求所需要的

You are incorrectly indexing your JSON object and adding a new key named 'title' in the root of the object, while you are trying to update the value inside the array. 您试图更新数组中的值时,错误地为JSON对象建立索引并在该对象的根目录中添加名为“ title”的新键。 In your case, you should be accessing res['requests'][0]['addSheet']['properties']['title'] = new_date 就您而言,您应该访问res['requests'][0]['addSheet']['properties']['title'] = new_date

I now realize I can pass my variables directly in the json. 我现在意识到我可以直接在json中传递变量。

prev_date =  datetime.date.today()-datetime.timedelta(1)
new_date = str(prev_date.isoformat())
req = {
"requests": [
{
"addSheet": {
"properties": {
"title": new_date
}
}

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

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