简体   繁体   English

如何将json对象转换为指定的json格式

[英]how to convert json object to a specified json format

how to convert如何转换

[{
    "10001": 30,
    "10002": 30,
    "10003": 50
}] 

to

"fare": {
    "10001": {
        "10002": 30,
        "10003": 50
    },
    "10002": {
        "10001": 30,
        "10003": 30
    },
    "10003": {
        "10001": 50,
        "10002": 30
    }
} 

using javascript使用 JavaScript

You should maybe learn more about algorithm and javascript to solve this problem as it is a specific example and not a general problem.您可能应该了解更多关于算法和 javascript 的知识来解决这个问题,因为它是一个具体的例子,而不是一个普遍的问题。

But this code do the trick :但是这段代码可以解决问题:

 var json = [{ "10001": 30, "10002": 30, "10003": 50 }]; var finalJson = {}; finalJson["fare"] = {}; Object.keys(json[0]).map(k1 => { finalJson["fare"][k1] = {}; Object.keys(json[0]).filter(k2 => k1 !== k2).map(k2 => { finalJson["fare"][k1][k2] = json[0][k2]; }); }); console.log(finalJson);

Maybe is better to understand the differences a bit more:也许更好地理解这些差异:

This is 1 Array with 3 properties inside这是 1 个Arrayproperties inside有 3 个properties inside

[{
    "10001": 30,
    "10002": 30,
    "10003": 50
}]

and this is 1 'Object with 3 Properties that have an Object within这是 1 'Object with 3 Properties that have an Object within

"fare": {
    "10001": {
        "10002": 30,
        "10003": 50
    },
    "10002": {
        "10001": 30,
        "10003": 30
    },
    "10003": {
        "10001": 50,
        "10002": 30
    }
}

JSON could take any of the above, it just depends on what you will be doing with the data. JSON 可以采用上述任何一种方式,这取决于您将如何处理数据。

This link might help you understand more about JSON notation.此链接可能会帮助您了解有关 JSON 表示法的更多信息。 Hope this helps https://www.w3schools.com/js/js_json_intro.asp希望这有助于https://www.w3schools.com/js/js_json_intro.asp

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

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