Generating intricate JSON structures with JavaScript programming instructions

In the world of JSON, I am still a novice. I need to use JavaScript to construct the JSON structure below, but I'm struggling with adding the second element ("12101") and populating the people in the JSON Structure. Below is the code I tried, however, it does not achieve what I need:

var chat = {};
chat = {"101":{}};
chat["101"].people= {};
chat["101"].people = {"L0b12leL-Ar9GYKoAAAC":{}};
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2c3331283b371a2b3f393274393537">[email protected]</a>"};
chat["101"].room= {};

The desired JSON structure:

{
  "101": {
    "people": {
      "L0b12leL-Ar9GYKoAAAC": {
        "name": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dec1c3dac9c5e8d9dccdcbc086cbc7c5">[email protected]</a>",
        "inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "countrycode": "in",
        "device": "desktop",
        "roomname": "R1"
      },
      "qKCglYWI1hRhZUZCAAAD": {
        "name": "Ishim",
        "inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "roomname": "Ra"
      }
    },
    "room": {
      "f787f316-6424-491b-b779-cfc396f0f8a1": {
        "name": "R1",
        "id": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owner": "L0b12leL-Ar9GYKoAAAC",
        "people": [
          "L0b12leL-Ar9GYKoAAAC"
        ],
        "status": "available"
      },
      "2e52905d-951c-4990-b9b7-2f3fc0602922": {
        "name": "Ra",
        "id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owner": "qKCglYWI1hRhZUZCAAAD",
        "people": [
          "qKCglYWI1hRhZUZCAAAD"
        ],
        "status": "available"
      }
    }
  },
  "12101": {
    "people": {
      "K-Ar9GYKoAAAC": {
        "name": "Rahul.com",
        "inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "countrycode": "in",
        "device": "desktop",
        "roomname": "R1"
      },
      "I1hRhZUZCAAAD": {
        "name": "Vipul",
        "inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "roomname": "Ra"
      }
    },
    "room": {
      "b779-cfc396f0f8a1": {
        "name": "Rahul-R1",
        "id": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owner": "L0b12leL-Ar9GYKoAAAC",
        "people": [
          "L0b12leL-Ar9GYKoAAAC"
        ],
        "status": "available"
      },
      "b9b7-2f3fc0602922": {
        "name": "Vipul-Room1",
        "id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owner": "qKCglYWI1hRhZUZCAAAD",
        "people": [
          "qKCglYWI1hRhZUZCAAAD"
        ],
        "status": "available"
      }
    }
  }
}

Answer №1

This example is considered invalid due to the presence of dashes in the property name.

chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9afb0b2abb8b499a8bcbab1f7bab6b4">[email protected]</a>"};

To correctly access this, ensure that it is enclosed within quotes

chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4137282a33202c01302422296f222e2c">[email protected]</a>"};

Answer №2

Utilize bracket notation as a property accessor like in the following example:

chat["12101"].people = {};
chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"[email protected]"};

By using bracket notation, you can easily access properties without worrying about valid identifier names. This is especially useful when working with strings like "L0b12leL-Ar9GYKoAAAC".

It's important to remember that in JSON, any string can be used as a property name as long as it is enclosed in quotes. For example, {"L0b12leL-Ar9GYKoAC":true} is just as valid as {"💖":true}.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble Loading HTML Template Post Email Dispatch in Django

In my Django project, I have set up functionality to send an email after a form submission using the smtplib module. The email is sent successfully, but for some reason, I'm encountering an issue where the corresponding HTML template (delivery_email_s ...

How to transfer identification from one AngularJS page to another

I need help figuring out how to retrieve an ID from the list.html page and use that same ID to display corresponding details on the list-detail.html page. I am new to using angularjs and struggling with getting the details based on the ID. Below is my code ...

"Why is the comparison function of bcryptjs returning null even though the hash being used is the one that was generated

For security purposes, I securely store hashed passwords in MongoDB. However, when I attempt to compare the stored password with a user-entered string, bcryptjs returns a null value. https://i.stack.imgur.com/4sTXM.png The hashed password is stored in bin ...

React: automatically close other SubMenus when a new SubMenu is opened

Is there a way to automatically close all other open SubMenus when a user opens a new SubMenu? If anyone has a solution, I would greatly appreciate the help! This is my code: Menu.tsx -> const Menu: React.FC = ({ data }) => { return ( ...

Encountering a critical issue with Angular 12: FATAL ERROR - The mark-compacts are not working effectively near the heap limit, leading to an allocation failure due

After upgrading my Angular application from version 8 to 12, I encountered an issue. Previously, when I ran ng serve, the application would start the server without any errors. However, after updating to v12, I started receiving an error when I attempted t ...

Azure Function: Eliminate duplicate data in JSON from two many-to-many relationships into a single table

I am facing an issue where I have multiple many-to-many tables mapping to a single table, resulting in duplicate data that needs to be removed from the JSON output. Additionally, the Ingredients and Conditions are displayed as lists, causing duplication of ...

Is there a way to convert HTML character codes to their corresponding characters in text retrieved from selenium scraping before adding it to an sqlite database?

Currently, I am utilizing Selenium (Chromedriver) and Python 2.7 to extract dynamic text from a website enclosed within HTML tags. The text is nested in a JSON object, which generates a content list on the page being viewed. However, my primary focus is on ...

commitment to effectively managing errors and exceptions

Looking to create a function that can handle async operations and return a promise. Here's what I need it to do: Download external content using AJAX If the content cannot be downloaded (e.g. invalid URL) -> reject If the content is downloaded but c ...

Using jQuery's slideToggle feature to hide content when clicked again or when a different button is

I have a challenge with creating toggle buttons that require specific functions: 1) Display content on the first click (this is working) 2) Conceal content when another button is clicked (this is also working) 3) Hide content on the second click (this i ...

Express 4.13.4 appears to be disregarding the cookie's expiration date when the moment.toDate() function is used

I've been encountering an issue where I am attempting to set a cookie with a specific expiry date of 3 months, but the expiration is not setting correctly. Using momentJS, I created a date object for the desired time. The console confirms that the co ...

Is there a way to remove data from both a JSON file and an HTML document?

Currently, I am facing a challenge with my code. I am unsure how to implement the functionality to delete a row when clicking on the X button and retrieve the unique ID of that particular row to append it to the URL. Unfortunately, finding the correct meth ...

How can I conceal the element that came before in JavaScript?

<div onclick="toggleContent(this)" class="iptv"><div class="triangle"></div><b>LUZ HD</b> - 98 channels (including 32 HD channels) <div class="iptv_price"><b><img src="img/rj45.png" class="icon_ofert ...

An HTML document may display a segment of a URL

Is there a way to display part of a URL in an HTML document, so that if the URL changes, the corresponding content in the body also updates? For instance, www.example.com/?key=i - Is it possible for this link to be dynamically displayed within the body o ...

Traverse the initial three elements of an array using JavaScript (React)

Let's say we have a collection of 5 items: const items = [ {id: 1, name: 'book', price: 50}, {id: 2, name: 'phone', price: 450}, {id: 3, name: 'fish', price: 80}, {id: 4, name: 'apple', price: 5}, {id: 5, name: ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Enhanced Fancybox Version 2 adjusts iframe width to fit content

I have been attempting to adjust the width of the iframe in fancybox v2 to fit my content properly. However, every time I try, the content appears too large within the iframe and requires horizontal scrolling to view it all. My goal is to see the entire wi ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

Using jQuery for Dragging and Dropping Elements within Dynamically Loaded Divs with

Is it possible to drag an element on the page into a droppable element inside an ajax loaded div? The code works fine when the droppable element is placed directly in the regular page, but not within the ajax loaded div. It seems like the issue may be rela ...

Ensure that JSON requests do not contain line breaks within the <div> element

Storing data in a database using json/jquery/ajax has been successful for me. When I retrieve the data in a textarea, it displays exactly as expected. However, loading the data into a DIV results in the absence of line breaks. I have tried various CSS styl ...

Material UI Input Field, Present Cursor Location

Is there a way to retrieve the current cursor (caret) position in a MaterialUI text field? https://material-ui.com/components/text-fields/ I am looking to make changes to the string content at a specific index, such as inserting a character X between cha ...