When an object is passed through JSON.stringify, the resulting output is simply an

My attempt to convert a JavaScript object into JSON is not working as expected. When I use console.log(myObject), the object is displayed correctly.

However, when I try

console.log(JSON.stringify(myObject));
, I only get an empty object {}.

Can anyone point out what could be causing this issue? Please see below for the object in question:

 Object
  autor: "Administrador"
  descripcion: "At Google I/O 2015, everything we’ve seen and learned about is under the command of Sundar Pichai. In this exclusive interview, he walks us through his product vision."
  titulo: "The future of Google with Sundar Pichai"
  url_imagen: "https://i.ytimg.com/vi/TguamcqrQjI/sddefault.jpg"
  url_video: "https://www.youtube.com/embed/TguamcqrQjI"
  __proto__: Object

For clarification, here is how I am creating the object:

var myObject = {};
    $http.get('apiCallToYoutubeIcantShareHereCauseItContainsAPrivateKey')
    .success(function(data) {

      myObject.titulo = data['items'][0]["snippet"]['title'];
      myObject.descripcion = data['items'][0]["snippet"]['description'];
      myObject.url_video ="https://www.youtube.com/embed/"+idYoutube;
      myObject.url_imagen = data['items'][0]["snippet"]['thumbnails']['standard']["url"];
      myObject.autor = 'Administrador';
    });

Answer №1

It appears that you may be attempting to print the object before it has been received from the server (

This is due to an asynchronous request
). Consider waiting until the success message is triggered, or implementing concepts such as Promises/Deferred.

var myObject = {};
    $http.get('apiCallToYoutubeIcantShareHereCauseItContainsAPrivateKey')
    .success(function(data) {

      myObject.titulo = data['items'][0]["snippet"]['title'];
      myObject.descripcion = data['items'][0]["snippet"]['description'];
      myObject.url_video ="https://www.youtube.com/embed/"+idYoutube;
      myObject.url_imagen = data['items'][0]["snippet"]['thumbnails']['standard']["url"];
      myObject.autor = 'Administrador';

      console.log(JSON.stringify(myObject));
    });

Answer №2

The reason for the error is due to the presence of 2 semicolons ; inside your object where they are not supposed to be.

Your current code:

var myObject = {
    "autor": "Administrador",
    "descripcion": "At Google I/O 2015, everything we’ve seen and learned about is under the command of Sundar Pichai.In this exclusive interview, he walks us through his product vision.Subscribe: goo.gl/G5RXGsFollow on Twitter: goo.gl/XTWX61↵Follow on Instagram: goo.gl/7ZeLvX ",
    "titulo": "The future of Google with Sundar Pichai",
    "url_imagen": "i.ytimg.com/vi/TguamcqrQjI/sddefault.jpg";, // <-- Semicolon that doesn't belong here
    "url_video": "youtube.com/embed/TguamcqrQjI"; // <-- Semicolon that doesn't belong here
};

By removing the unnecessary semicolons from the Object:

JSFiddle: http://jsfiddle.net/zu2L3h5x/1/

var myObject = { 
    "autor": "Administrador",
    "descripcion": "At Google I/O 2015, everything we’ve seen and learned about is under the command of Sundar Pichai.In this exclusive interview, he walks us through his product vision.Subscribe: goo.gl/G5RXGsFollow on Twitter: goo.gl/XTWX61↵Follow on Instagram: goo.gl/7ZeLvX ",
    "titulo": "The future of Google with Sundar Pichai",
    "url_imagen": "i.ytimg.com/vi/TguamcqrQjI/sddefault.jpg",
    "url_video": "youtube.com/embed/TguamcqrQjI"
}; 

Answer №3

Have you double-checked that myObject is still within scope when you run

console.log(JSON.stringify(myObject));

If you try the following code in the console, it should work without any issues:

var web = { "domain":"mammothworkwear.com","keywords":["Helly Hansen", "Snickers"]}; console.log(JSON.stringify(web));

It seems like your myObject might be empty

Edit:

The JSON you provided does not validate; you can check its formatting on http://jsonlint.com/

If you correct the formatting errors and execute it all in the console, it will work as intended:

var myObject = {
    autor: "Administrador",
    descripcion: "At Google I/O 2015, everything we’ve seen and learned about is under the command of Sundar Pichai. In this exclusive interview, he walks us through his product vision.↵↵Subscribe: http://goo.gl/G5RXGs↵↵Check out our full video catalog: http://goo.gl/lfcGfq↵Visit our playlists: http://goo.gl/94XbKx↵Like The Verge on Facebook: http://goo.gl/2P1aGc↵Follow on Twitter: http://goo.gl/XTWX61↵Follow on Instagram: http://goo.gl/7ZeLvX↵Read More: http://www.theverge.com",
    titulo: "The future of Google with Sundar Pichai",
    url_imagen: "https://i.ytimg.com/vi/TguamcqrQjI/sddefault.jpg",
    url_video: "https://www.youtube.com/embed/TguamcqrQjI"
}; 
console.log(myObject); 
console.log(JSON.stringify(myObject));

Answer №4

There is a chance that the error in your JSON.stringify call is being intercepted somehow, leading to the result appearing as an empty object. However, pinpointing the exact issue would require analyzing the actual code and understanding its context.

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

What are some ways to decrease the size of a JSON object?

I've generated a JSON file from querying a database using SQL. My aim is to condense multiple lines of the same "car_id" into a single line. Here's an example of my JSON file with several entries for a single car: [{"car_id":"1","sca_multiversei ...

Prevent postback in a LinkButton by disabling the default behavior when connecting it to a jQuery

I am struggling with preventing the page from posting back when clicking on a link button that I have bound to a click event using jQuery. Despite my attempts, the page always posts back, even though I have tried using event.preventDefault as suggested he ...

Guide to creating a grammar in ANTLR4 for JSON data structures

I'm struggling with creating an ANTLR4 grammar for abstract data structures. Let's take the example of a Python program that deals with a list of people, where each person has a name, email address, and phone number. This abstract data structure ...

Always display all options in MUI Autocomplete without any filtering

I am seeking to eliminate any filtering in the MUI Autocomplete component. My goal is for the text field popper to display all available options. The results are obtained from a server-side search engine. These results, or "hits," already provide a filter ...

What is the most effective method for parsing application/json MIME type with Jersey @Consumes in Java?

How can my Jersey webapp effectively handle JSON on POST requests using the @Consumes annotation and store it in a variable? My current method is as follows: @Path("/postask") @POST @Consumes("application/json") @Produces("text/plain") public String postA ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

Why hasn't the styles folder been generated in Nuxt 3?

After running the command "npx nuxi generate," the css folder does not seem to be created in the static site. What could be the issue? package.json: { "private": true, "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": ...

431 - (Excessive Request Header Size)

First time asking for help, please take that into consideration What I've tried: I cleared my Google Chrome cache and cookies, attempted incognito mode, updated to the latest node version, but still encountering the same error. Error message in Chro ...

Displaying a PHP array in alphabetical order within a dropdown menu option

After retrieving the Google Sheet JSON output and converting it into a PHP array, I am currently facing an issue where I need to filter the data by football club and display them in alphabetical order. The current result is a dropdown list of football club ...

Enhancing Rails JSON Output

Check out the following code snippet: render json: news, :include => {:tags => {:only => :name}, :category => {:only => :name}}. Here is the output it generates: { "id": 2, "title": "title", "tags": [], "category": { "name": "lorem" } I ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

problem encountered when loading an HTML file within another HTML file using AJAX

By clicking a button, I successfully loaded a full HTML page (refer to the structure below) into another HTML page. <!--START:HTML to be loaded by ajax--> <head> <!--START: The content inside this head tag is not processed while the pag ...

displaying a PDF file in Safari

Is there a way to display a PDF document within an HTML page without encountering a missing plugin error? I attempted to use the following code, but the error persists. Interestingly, if I drag the same PDF file directly into my browser, it displays perfe ...

Display laravel view using JavaScript Ajax

I seem to be facing a challenge in displaying the desired view after invoking the controller method via Ajax. Below is the JavaScript function where I trigger the controller Method 'create_pedido' using an Ajax post request. $('.small-box&a ...

Continue with the transaction by utilizing the window.open method

I have encountered a situation where the payment processor providing me with a URL to direct the user. In this scenario, I can define success_url and cancel_url parameters where the user will be directed post payment completion. However, my application ...

The error message "Cannot access documentElement property of null in Ajax" indicates a problem with finding the documentElement

After following along with the Ajax tutorial from The New Boston, I encountered an issue where the code I wrote was not working on my computer as expected. When using Google Chrome: Uncaught TypeError: Cannot read property 'documentElement' of ...

Having trouble with accessing environment variables dynamically in NextJS

I'm encountering an issue where I can't access environment variables dynamically in NextJS. Inside my .env.local file, I have the following entry: NEXT_PUBLIC_TEST=test Within my _app.tsx file, I've written the following code: const test = ...

How is UI Router Extras causing unexpected errors in my unit tests?

QUESTION: - I am facing failures in my tests after installing ui-router-extras. How can I resolve this issue? - Is there a way to use ui-router-extras without causing test failures? If you want to quickly install this, use yeoman along with angular-full ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

Implementing an Onclick function in HTML

I have an HTML code and I am looking to add an onclick event for a button named GET DATA. When the button is clicked, I want to send data for userId and categoryId to a PHP file. Can someone help me implement this functionality in my existing code? Here ...