简体   繁体   English

获取 json/dict 字符串的值

[英]get value of a json/dict string

I have following string:我有以下字符串:

"root['bananas']['costs'][0]"

I want to get costs out of it in a reusable way -> the value I want to extract will always before the [0].我想以可重用的方式从中获取costs -> 我想要提取的值将始终在 [0] 之前。 What is the best way to do this?做这个的最好方式是什么?

Well If you want to get the element before the last one (with no relation if its a zero or not) and you know that you would have quotes ' ' wrapped around the target word you could use something like this:好吧,如果你想在最后一个元素之前获取元素(如果它是零则没有关系)并且你知道你会在目标词周围加上引号' ' ,你可以使用这样的东西:

str = "root['bananas']['costs'][0]"

str.split("[")[-2].rstrip("']").lstrip("'")

Again if your output is more random than this solution will have to be edited.同样,如果您的 output 比此解决方案更随机,则必须对其进行编辑。

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

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