我的JSON文件如下:
{"A":[
{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp", "C":{....},
{"Timestamp": "2017-11-14 14:40:32", "File": "E.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:41:32", "File": "E.kmp", "L":{....},
................................................................,
{"Timestamp": "2017-11-14 14:42:32", "File": "D.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:43:32", "File": "D.kmp", "L":{....}
]
我想将所有“文件”名称更改为“E.kmp”。这就是为什么我需要用“E.kmp”替换“D.kmp”。如果有可能用python或R,请帮助我。 Python是首选。
答案 0 :(得分:1)
以下是public function search_professional()
{
if($this->input->is_ajax_request())
{
$professional = $this->UserModel->search_professional($this->input->post('location_id',true),$this->input->post('category_id',true));
foreach ($professional as $row)
{
echo '
<li>
<a class="s_pro" href="'.site_url('Professional/show_professional_detail/'.$row->pro_id).'">'.$row->firstname.' '.$row->lastname.'<br /><span>Description...</span></a></i>';
}
}
else
{
show_404();
}
}
R
library(jsonlite)
library(tidyverse)
res <- fromJSON(json_val) %>%
map(mutate, File = 'E.kmp') %>%
toJSON
prettify(res, indent=1)
# {
# "A": [
# {
# "Timestamp": "2017-11-14 14:39:54",
# "File": "E.kmp"
# },
# {
# "Timestamp": "2017-11-14 14:49:54",
# "File": "E.kmp"
# },
# {
# "Timestamp": "2017-11-14 14:59:54",
# "File": "E.kmp"
# }
# ]
#}
答案 1 :(得分:0)
只需将D.kmp
替换为E.kmp
import json
text = '''
{"A":[
{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp", "C":{....},
{"Timestamp": "2017-11-14 14:40:32", "File": "E.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:41:32", "File": "E.kmp", "L":{....},
................................................................,
{"Timestamp": "2017-11-14 14:42:32", "File": "D.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:43:32", "File": "D.kmp", "L":{....}
]
'''
json_data = json.loads(text)
for element in json_data["A"]:
if element["File"] == "D.kmp":
element["File"] = "E.kmp"
答案 2 :(得分:0)
由于我无法看到您的整个JSON结构,以下是使用replace()
的方法。with open('file.json', 'r') as file :
data = file.read()
data = data.replace('"File": "D.kmp"', '"File": "E.kmp"')
with open('file.json', 'w') as file:
file.write(data)
答案 3 :(得分:0)
我想有简单的方法:
your_json['A'] =[i for i in your_json['A'] if not i.update({"File":"D.kmp"})]
答案 4 :(得分:0)
一个简单的解决方案是使用for循环迭代字典并替换值。
json_val = {"A":[{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp"},
{"Timestamp": "2017-11-14 14:49:54", "File": "D.kmp"},
{"Timestamp": "2017-11-14 14:59:54", "File": "D.kmp"}
]}
for dic in json_val['A']:
if dic['File'] != 'E.kmp':
dic['File'] = 'E.kmp'
print json_val
如果值不是File
,则上面的代码段会替换列表中所有词典中的键E.kmp
的值。
你不需要json.loads(json_val)
,因为python可以处理json。
输出将为:
{'A': [{'Timestamp': '2017-11-14 14:39:54', 'File': 'E.kmp'},
{'Timestamp': '2017-11-14 14:49:54', 'File': 'E.kmp'},
{'Timestamp': '2017-11-14 14:49:54', 'File': 'E.kmp'}
]}