burcubelen
burcubelen

Reputation: 23

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?

Upvotes: 1

Views: 1523

Answers (1)

Timur
Timur

Reputation: 2287

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/[email protected]/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)

Upvotes: 1

Related Questions