Home > Blockchain >  how to obtain specific "key" from json stringify (my case)?
how to obtain specific "key" from json stringify (my case)?

Time:12-14

I need to obtain "class" key on this json :

var data = [{"loc":[7.876110076904297,48.79586219787598,577.145938873291,427.3995780944824],"class":"low","score":0.752582848072052}]

If I try to console.log(data) it return "object, Object"

If I try to

var json : json.stringify(data)
console.log(json)

the result is

[{"loc":[7.876110076904297,48.79586219787598,577.145938873291,427.3995780944824],"class":"low","score":0.752582848072052}]

I already to map it but failed

var json = json.stringify(data)
var string = map.json(loc => loc.class)
console.log(string)

the result is "map.json is not a function"

I try to parse it but console show error

var json = json.parse(data)

the result is error

If I do this

var json = json.stringify(data)
console.log(json[5])

console return l, i guess this is 5th word on the var data

How I can get "class" key? or do I need to count the word one by one, if yes how to know the specific word length on "class" key?

CodePudding user response:

The JSON.stringify method takes a usable data structure and converts it to a string.

The string is fantastic for storing (e.g. in localStorage) or transmitting over the network (e.g. in an Ajax request).

It is useless for working with.

Work with your original data structure instead.

var data = [{
  "loc": [7.876110076904297, 48.79586219787598, 577.145938873291, 427.3995780944824],
  "class": "low",
  "score": 0.752582848072052
}]

const object = data[0];
const value = object.class;
console.log(value);

CodePudding user response:

The map() method creates a new array populated with the results.

const data = [{"loc":[7.876110076904297,48.79586219787598,577.145938873291,427.3995780944824],"class":"low","score":0.752582848072052}];

const classes = data.map(loc => loc.class);
console.log(classes)

It seems like your array only contain just one object, so if instead of an array you just want the class value, you can just reference it.

const data = [{"loc":[7.876110076904297,48.79586219787598,577.145938873291,427.3995780944824],"class":"low","score":0.752582848072052}];

const res = data[0].class;
console.log(res)

CodePudding user response:

var data = [{"loc":[7.876110076904297,48.79586219787598,577.145938873291,427.3995780944824],"class":"low","score":0.752582848072052}];

var json = data[0]["class"]

console.log(json);

CodePudding user response:

var data = [{"loc":[7.876110076904297,48.79586219787598,577.145938873291,427.3995780944824],"class":"low","score":0.752582848072052}]
console.log(data[0].class)
var a= data[0].class;
alert(JSON.stringify(a))

you can get class data from it in this way

var data = [{"loc":[7.876110076904297,48.79586219787598,577.145938873291,427.3995780944824],"class":"low","score":0.752582848072052}]
console.log(data[0].class)

Here is the example

  • Related