我正在阅读一个Json,它是像这样的几本字典的列表:
a_list = [ {
"ID": "20394820938",
"data": [
{
"fruit": "tomato",
"provider": "walmart",
"availability": "True",
"Type": false
},
{
"fruit": " orange ",
"Type": false
},
{
"fruit": "watermelon",
"provider": "destination",
"availability": "cotsco",
"Type": false
},
{
"fruit": " the watermelon is new",
"Type": false
}
],
"API": false,
"count": 0
},
{
"ID": "203948lHBFNPO",
"data": [
{
"fruit": "apple",
"provider": "walmart",
"availability": "True",
"Type": false
},
{
"fruit": " this is a tomato ",
"Type": false
},
{
"fruit": "lemon",
"provider": "unknown",
"availability": "cotsco",
"Type": false
},
{
"fruit": " orange ",
"Type": false
},
{
"fruit": "banana",
"provider": "unknown",
"availability": "unknown",
"Type": false
}
],
"API": false,
}
]
当且仅当词典的子元素之一中包含字符串IM00N
时,才如何将apple
附加到Json的id值?例如:
a_list = [ {
"ID": "20394820938",
"data": [
{
"fruit": "tomato",
"provider": "walmart",
"availability": "True",
"Type": false
},
{
"fruit": "apple",
"Type": false
},
{
"fruit": "watermelon",
"provider": "destination",
"availability": "cotsco",
"Type": false
},
{
"fruit": " the watermelon is new",
"Type": false
}
],
"API": false,
"count": 0
},
{
"ID": "IM00N-203948lHBFNPO",
"data": [
{
"fruit": "apple",
"provider": "walmart",
"availability": "True",
"Type": false
},
{
"fruit": " this is a tomato ",
"Type": false
},
{
"fruit": "lemon",
"provider": "unknown",
"availability": "cotsco",
"Type": false
},
{
"fruit": " orange ",
"Type": false
},
{
"fruit": "banana",
"provider": "unknown",
"availability": "unknown",
"Type": false
}
],
"API": false,
}
]
我试图构建一个正则表达式,但是它很困难,因为列表中每个子字典的元素中没有模式。进行这种匹配和替换的正确方法是什么?
答案 0 :(得分:3)
您可以使用for循环修改数据:
echo htmlentities('An example <br>'); // This will print - An example < br >
echo htmlentities('µ †'); // This will print - µ †
如果数据的形状有所不同,以致某些条目没有if let postNote = posts[indexPath.item].postNote {
if(postNote.isEmpty) {
socialCell.noteTextView.removeFromSuperview()
socialCell.postDetailsView.bottomAnchor.constraint(equalTo: socialCell.noteTextView.bottomAnchor).isActive = false
socialCell.postDetailsView.bottomAnchor.constraint(equalTo: socialCell.postName.bottomAnchor).isActive = true
}
}
键,则可以捕获for entry in a_list:
if any('apple' in item['fruit'] for item in entry['data']):
entry['ID'] = 'IM00N-' + entry['ID']
或使用fruit
KeyError