简体   繁体   中英

Convert Json to JS Object with Python

I have some excel files. I want to convert them to JS Objects. I can convert as Json like below.

{ "profileMenu.info": "Profile information",
        "profileMenu.infos.generalInfo": "general information",
        "profileMenu.infos.otherInfos": "Other information" }

I need to convert them like this.

  profileMenu: {
    info: 'Profile information',
    infos: {
      generalInfo: 'general information',
      otherInfos: 'Other information',
    } 

I have searched for ways to do this but couldn't find any. Can you please help me on how to convert this Json to JS Objects?

If you are open to using external libraries,

In javascript, you can do this with lodash :

 var myJSON = { "profileMenu.info": "Profile information", "profileMenu.infos.generalInfo": "general information", "profileMenu.infos.otherInfos": "Other information" } let myObject = {} for (key in myJSON) { _.set(myObject, key, myJSON[key]); } console.log(myObject)
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

In Python, you can do this with pydash :

import pydash

myJSON = {
  "profileMenu.info": "Profile information",
  "profileMenu.infos.generalInfo": "general information",
  "profileMenu.infos.otherInfos": "Other information"
}

myObject = {}

for key in myJSON:
  pydash.set_(myObject, key, myJSON[key])
  
print(myObject)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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