How can I convert a string to nested Json?

  • 0
    I have a map like this.
    let map= new Map([["80-c4-48-84-79", " Federal research and production center "],
    ["73-b3-49-af-9d"," dgru"],
    ["04-d2-45-86-6a","Main"],
    ["d0-51-41-bf-4f", " Publications"],
    ["c5-3c-4d-83-4f", " news"],
    ["7d-ae-46-a0-25", "Contacts"],
    ["8f-01-4b-81-4e", "Certification center"],
    ["56-32-40-82-1a","1959"],
    ["27-63-47-b9-1c","2019"],
    ["a7-34-46-b8-38"," Moscow"],
    ["42-29-4c-bb-df"," text"],
    ["67-8b-47-b1-34","example"]]);


    I am trying to convert the map to json. It turns out such a clumsy code
    let str="{room: {" 
    let stroka;
    
    for(let keysMap of map.keys()) {
      stroka += "\""+keysMap+"\""+ " : "+"\""+ map.get(keysMap)+"\""+","
    }
    let rezultat= str+ stroka + "}}"
    console.log(rezultat)


    This is the result
    {room: {undefined"80-c4-48-84-79" : " Federal research and production center ","73-b3-49-af-9d" : " dgru","04-d2-45-86-6a" : "Main","d0-51-41-bf-4f" : " Publications","c5-3c-4d-83-4f" : " news","7d-ae-46-a0-25" : "Contacts","8f-01-4b-81-4e" : "Certification center","56-32-40-82-1a" : "1959","27-63-47-b9-1c" : "2019","a7-34-46-b8-38" : " Moscow","42-29-4c-bb-df" : " text","67-8b-47-b1-34" : "example",}}


    Can it be done more beautifully? Found this example LINK
    But there is no nested json, but I need it to look like this.
    {TEXT: {"text1": "text1", "text2": "text2" ......}}
    JavaScript Xander Garner, Apr 12, 2020

  • 1 Answers
  • 0
    const result = JSON.stringify({ room: Object.fromEntries(data) });
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!