1

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?

4
  • { profileMenu.info: "Информация о профиле", that is no valid JSON. In JSON keys have to be enclosed in double-quotes. Besides that, if you have something as JSON encoded string, you can just copy and past it into JS code and use it as a JavaScript Object. Data encoded as JSON is a valid representation of a JavaScript Object in JS code. Commented Dec 7, 2021 at 11:12
  • 1
    Hmm, what does the JSO in JSON stand for? Commented Dec 7, 2021 at 11:13
  • Does this answer your question? Generate a nested object structure by string key/path Commented Dec 7, 2021 at 11:23
  • @t.niese You're right I have double-quotes in Json keys. I editted. Commented Dec 7, 2021 at 11:25

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.