我有一个特定格式的json文件,但我想将其更改为需要拾取其中一个嵌套值并将其投影为上级键的格式
我只尝试了stackoverflow的建议,但很累,无法达到特定的嵌套值,但是我无法提高它。
data = open('sampleDemo.json','r')
json_decode=json.load(data)
for item in data:
mydict={}
mydict['spk1'] = item.get('audioResponse').get('startTime').get('emotion').get.....
print mydict
所需的输出:
输入文件如下:
{
"audioResponse": [
{
"speaker":"spk1",
"startTime": "0.0",
"endTime": "15.239",
"emotion": "neutral",
"emotionScore": "0"
},
{
"speaker":"silence",
"startTime": "15.240",
"endTime": "16.900",
"emotion": "NA",
"emotionScore": "NA"
},
{
"speaker":"spk2",
"startTime": "16.932",
"endTime": "27.320",
"emotion": "happy",
"emotionScore": "2"
},
{
"speaker":"spk1",
"startTime": "27.977",
"endTime": "37.900",
"emotion": "anger",
"emotionScore": "-3"
}
]}
答案 0 :(得分:2)
var data = {
"audioResponse": [{
"speaker": "spk1",
"startTime": "0.0",
"endTime": "15.239",
"emotion": "neutral",
"emotionScore": "0"
}, {
"speaker": "silence",
"startTime": "15.240",
"endTime": "16.900",
"emotion": "NA",
"emotionScore": "NA"
}, {
"speaker": "spk2",
"startTime": "16.932",
"endTime": "27.320",
"emotion": "happy",
"emotionScore": "2"
}, {
"speaker": "spk1",
"startTime": "27.977",
"endTime": "37.900",
"emotion": "anger",
"emotionScore": "-3"
}]
};
var result = {
audioResponse: []
};
for (var item of data.audioResponse) {
var existed = result.audioResponse.find(x => x[item.speaker]);
if (!existed)
result.audioResponse.push({
[item.speaker]: []
});
existedArray = result.audioResponse.find(x => x[item.speaker])[item.speaker];
var copy = {...item};
delete copy.speaker;
existedArray.push(copy);
}
console.log(result);
答案 1 :(得分:1)
var inputList = {
"audioResponse": [
{
"speaker":"spk1",
"startTime": "0.0",
"endTime": "15.239",
"emotion": "neutral",
"emotionScore": "0"
},
{
"speaker":"silence",
"startTime": "15.240",
"endTime": "16.900",
"emotion": "NA",
"emotionScore": "NA"
},
{
"speaker":"spk2",
"startTime": "16.932",
"endTime": "27.320",
"emotion": "happy",
"emotionScore": "2"
},
{
"speaker":"spk1",
"startTime": "27.977",
"endTime": "37.900",
"emotion": "anger",
"emotionScore": "-3"
}
]}
var result = inputList.audioResponse.reduce((acc, {speaker, ...rest})=>{
acc['audioResponse'][speaker] = (acc['audioResponse'][speaker]) || [];
acc['audioResponse'][speaker].push(rest);
return acc;
}, {audioResponse:{}});
console.log(result);
您可以使用reduce方法。希望对您有帮助!
答案 2 :(得分:0)
但是我想将其更改为需要选择其中一个嵌套值并将其投影为上级键的格式
您可以将组的属性设置为动态
'use strict';
let attribute = 'speaker'; // can be 'speaker' or 'emotion' or 'emotionScore'
let output = {
audioResponse: []
};
for (let response of data.audioResponse) {
let groupKey = response[attribute];
let group = output.audioResponse[groupKey];
delete response[attribute]; //remove the key
if (group) {
group.push(response);
} else {
group = [response];
}
output.audioResponse[groupKey] = group;
}
console.log(output);