Home > Software engineering >  How to get JSON Array value? I need to get murali printed
How to get JSON Array value? I need to get murali printed

Time:02-16

<!DOCTYPE html>
<html>
<body>

<h2>Creating an Array from JSON</h2>
<p id="demo"></p>

<script>
const myJSON = '[{password:"murali"}]';
const myArray = JSON.parse(myJSON).password;
document.getElementById("demo").innerHTML = myArray;
</script>

</body>
</html>

I need to get murali to get printed. This is for my React Project. I got to validate password. Hence I connected my mysql and retrive password from database and I need to validate it, In oder to validate I need to compare (database Password == input password). But as i retrive password I got the password in [{password: "murali"}] in this format and I am not able to compare with input password.

CodePudding user response:

I did not understand how the front-end code articulate with the back-end code, but to your simple question, you need to:

  • name your variable correctly, myArray seems to be a password and not an array
  • use double quotes for json keys
  • access array with an index

Fixed, this code will print the password.

const jsonString = '[{"password":"murali"}]';
const json = JSON.parse(jsonString);
const password = json[0].password;
document.getElementById("demo").innerHTML = password;
<div id="demo"></div>

CodePudding user response:

Just pointing out the issues preventing the code from running:

  1. The JSON string format is incorrect.
  2. The password object is the first item in an array so it must be retrieved using an index.
const myJSON = '[{"password":"murali"}]';       // <-- add double quotes to key
const myArray = JSON.parse(myJSON)[0].password; // <-- add array index 
  • Related