Building a properly formatted JSON object using JavaScript

I have been using the following code to build a JSON object with specific data:

{"contacts":[{"provider":"Yahoo","firstName":"myname","lastName":"surname","nickname":"mynick","email":"example@example.com","photoURL":"http://l.yimg.com/dh/ap/social/profile/profile_bxx.png"}]};

var data = {};
var contacts;
var gc = $.when(gigya.socialize.getContacts({callback: function(response){
  data['contacts'] = response.contacts.asArray();
}}));
gc.done(function(response) {
  contacts = data;
});
console.log(contacts);

However, when I try to pass this contacts object to a Google soy template, there seems to be an issue with the structure of the JSON object.

Can someone provide guidance on how to properly construct a valid JSON object using the code above?

Thank you for your assistance.

Answer №1

The item appears to be in good condition.

Consider using the JOSN.stringify() function, as shown in this jsFiddle example
or utilizing JSON.parse()

As demonstrated in the example, you can convert an object into valid JSON and then reverse it back into a valid JavaScript object.


In reference to your code:

  1. What information are you receiving from response?
  2. Also, why are you including response here if you are not using it?

    gc.done(function(response) {
      contacts = data;
    });
    

I suggest updating this line EDITED:

data['contacts'] = response.contacts.asArray();

to

contacts = JSON.parse(response.contacts);

and removing:

gc.done(function(response) {
  contacts = data;
});

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

Set the scroll position to the top left corner (0,0) when a link to the current route is clicked or pressed

In my React application, I am faced with a challenge. When the user is on the route /gallery/images and clicks on a link (such as <a> or <Link> from react-router-dom) that leads to the same route currently being displayed, how can I detect thes ...

Display popup just one time (magnific popup)

Attempting to display this popup only once during a user's visit. It seems like I might be overlooking something. <script src="http://code.jquery.com/jquery-1.7.min.js"> <link href="http://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1 ...

Step by step guide on serializing two forms and an entire table

I have been attempting to serialize data from two forms and the entire table simultaneously. While the form data is successfully serialized, I am encountering difficulty in serializing the table records as well. Below is the code snippet of what I have att ...

What is the process for utilizing the JWT token on the front-end after obtaining it?

After hours of research, I am still struggling to implement login functionality using JWT Tokens. Here is my progress so far: My login API const loginUser = async (req, res, next) => { try { const {username, password} = req.body //g ...

Create a slider feature on a webpage using the Google Maps API

A webpage has been created using the Google Map API. JSfiddle function initMap() { var intervalForAnimation; var count = 0; var map = new google.maps.Map(document.getElementById('map'), { cen ...

Show only the lower left quadrant within the img tag during the prepend operation

I'm attempting to add an <img> tag in front of a <div> similar to this example on JSFiddle. However, I have a specific requirement to only display the bottom left quarter of the image instead of the entire one. HTML Markup <div id="my ...

I am looking to create a PHP script that restricts access to individuals under the age of 18 based on the current

I'm looking for a way to use Php, javascript, or ajax to restrict access for individuals under 18 years old based on the current date. Any suggestions on how I can achieve this? Could someone please review my code for calculating age onblur or onSubm ...

Simple steps to trigger a PHP page from a JavaScript page by utilizing express functions

Currently, I am attempting to showcase a PHP page using JavaScript with express functions. Here is an illustration of the code: var express = require('express') var app = express() app.get('/', function (req, res) { res.send(' ...

Validate whether the datepicker HTML element contains a value before running a jQuery function

I have implemented a jquery datepicker in my form to select dates. In this setup, I am using jquery to check if the selected date is empty and also to verify if it falls on a Sunday. To address the issue of checking if the date is empty, I have utilized t ...

Leveraging Jackson Json for parsing Google Blogs articles

I've been facing difficulties in parsing this feed using the Jackson JSON Parser. Here's the feed: { "responseData": { "query": "Official Google Blogs", "entries": [ { "url": "http://googleblog.blogspot.com/feeds/posts/default", "title": "& ...

Sometimes, React doesn't cooperate properly in the callback function of a setState operation

Imagine this scenario: callback = () => { ... } When is it appropriate to use this.setState({...}, this.callback); and when should I opt for this.setState({...}, () => { this.callback(); }); In order to maintain the validity of this within the ...

Troubleshooting issues with jQuery `.live()` event not triggering as expected

In a project I am working on, I have implemented complex AJAX functionality to fetch inner page content from a WordPress blog. Due to the dynamic nature of the site, where the DOM is replaced after page load via AJAX, I have opted to use jQuery's .liv ...

merge a multidimensional array to create a dictionary object organized by keys

In my quest to construct a pricing structure for a product based on its color, size, and material, I have been grappling with the implementation process. Currently, I am maintaining a single JSON object that contains all possible options and attempting to ...

Embedding a line chart created with chart.js into an SVG container with the help of d3.js

My initial attempt was successful using a button element with the necessary classes and attributes. <button type="button" class="btn btn-default glyphicon glyphicon-arrow-left"></button> However, my next endeavor involve ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

I can't seem to figure out why the removeChild() function is not functioning properly in my

Recently, I've been working on a search website where users can input either a partial or full name and then click a button to display a list of actors whose names contain that specific string in a hint-like fashion. These names are sourced from a MyS ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

Utilize Chrome storage instead of localstorage to generate Parse sessions

I'm currently developing a Chrome Extension that relies on Parse User sessions. Because localstorage is limited to specific domains, I am looking to utilize chrome.storage so the data can be accessed across any site. The existing Parse Javascript SDK ...

Build failure encountered with create-react-app due to protracted duration followed by an error notification

When I created a react project version 15 and ran npm run build, it took an unusually long time (20 mins) and appeared to be frozen. Eventually, I encountered the following error. How can I resolve this issue? enter code heresers/rice/my-app-2/node_modu ...

Creating dynamic classes in VueJS

After carefully reviewing the documentation, I am puzzled about how to modify a class. My component's data is structured as follows: props: [ 'm_c_id', 'recipient_id', 'sender_id', 'userId' ], If sende ...