-1

I have a json file which contains data like this

{"name": "Mohamed"}

and in my js file I need to read the value in an array like this

[{value: "name"}]

how can I do this ?

Mhmd Elsaid
  • 11
  • 1
  • 3

2 Answers2

1

Use JSON.parse(data)

Such as

const ok = '{"name": "Mohamed"}';
const ok2 = JSON.parse(ok);
console.log(ok2.name);

Output will be Mohamed

MD Jahid Hasan
  • 786
  • 1
  • 9
  • 19
0

The data you have is JSON.stringify() data.

For example:

You have an object

var a = { name: 'Harsimar', admin: false }

To send that data to the server in a body, you converts the data into a string with this method called

var b = JSON.stringify(a); 

Now you have to data in this format (The object has become a string, now you cannot access the keys or data of the object directly)

b = "{"name":"Harsimar","admin":false}"

This is a one way to see, now the question you have asked is how we can use the string data as object. We need to reverse the proccess.

var c = JSON.parse(b)

So here, JSON.parse() is a method which we can use from converting the data from string -> object again. Now the variable c is equal variable a.

To put that object into an array, you can simply put it [c] and it will give output as you intend. [{ name: 'Harsimar', admin: false }]

harsimarriar96
  • 313
  • 2
  • 11