Home > Software engineering >  How to output a JSON string in JavaScript?
How to output a JSON string in JavaScript?

Time:03-30

I've looked everywhere on the internet and haven't found any solution. I want to output the latest release tag of my GitHub repo as an console.log(...) in JavaScript using the GitHub api. But how?

fetch('https://api.github.com/repos/{owner}/{repo}/releases/latest');
console.log(tag_name)

As much as I know, the GitHub APIs are in the JSON format. I just want to know

"tag_name": "v.1.1.1" 

the "v1.1.1". So the string output as a console.log

CodePudding user response:

Im guessing you are already requesting the data from the Github API, and storing it in a variable. You can get any JSON key by appending a . followed by the key you want to get. For example:

// Example JSON Object
const data = {
    version: "1.1.4",
    date: {
      day: "Monday",
      date: "12",
      month: "May",
      year: "2022",
    },
    users: [
      "Max",
      "John",
      "Jane",
      "Jack",
    ]
  }

// Get a element
console.log(data.version);
// Output: "1.1.4


// Get a element inside a element
console.log(data.date.month)
// Output: "May"

// Get a element inside a array
console.log(data.users[0])
//Output: "Max"

CodePudding user response:

Let's say you have an object called teacher

teacher:{ nameDetails:{firstName: 'John', lastName:'clinton'}, field:'Maths'}

Now lets say you want to console.log the firstName

You should write:

console.log(nameDetails.firstName)

Your JSON might contain arrays or anything else really.

You should consider console.log the JSON and provide it in your question so that anyone can give you a more specific answer.

  • Related