Firstly, here is the snippet of the json:
{
"messages":
[
{
"id": 460,
"type": "message",
"date": "2022-01-01T15:10:19",
"text": "hello, ",
},
{
"id": 461,
"type": "message",
"date": "2022-01-01T15:10:19",
"text":
[
"this ",
{
"type": "bold",
"text": "is"
},
" the ",
{
"type": "underline",
"text": "code"
},
" names."
]
},
{
"id": 462,
"type": "message",
"date": "2022-01-01T15:43:41",
"text":
[
"But, ",
{
"type": "bold",
"text": "list, set and string "
},
" are already builtin functions, so using these names is not recommended."
]
}
]
}
I would like to use Python to get all value of the "text" key, which locate in different level of the json, so I can merge them to a sentence as below:
Hello, this is the code names. but list, set and string are already builtin functions, so using these names is not recommended.
I've tried a bit with native dict manipulations and also tried the module Jmespath for json in Python, but I still can't workout a way to get it done. So you may know I am a newbie of Python, hope I can have a easy understand solution to achieve my goal here.
Thanks.
CodePudding user response:
You may handle the different datatype you can find dict,list,str
and apply the good logic
dict
: if value is a container : search in itlist
: search in all element of itstr
: add it
def search(data, search_key) -> str:
r = ''
if isinstance(data, dict):
for key, value in data.items():
if isinstance(value, (dict, list)):
r = search(value, search_key)
if isinstance(value, str) and key == search_key:
r = value
if isinstance(data, list):
for item in data:
r = search(item, search_key)
if isinstance(data, str):
r = data
return r
v = {"messages": [
{"id": 460, "type": "message", "date": "2022-01-01T15:10:19", "text": "hello, "},
{"id": 461, "type": "message", "date": "2022-01-01T15:10:19",
"text": ["this ", {"type": "bold", "text": "is"}, " the ",
{"type": "underline", "text": "code"}, " names."]},
{"id": 462, "type": "message", "date": "2022-01-01T15:43:41",
"text": ["But, ", {"type": "bold", "text": "list, set and string "},
" are already builtin functions, so using these names is not recommended."]}
]}
result = search(v, 'text')
print(result)
# hello, this is the code names.But, list, set and string are already builtin functions, so using these names is not recommended.