Kavvson
Kavvson

Reputation: 845

Get value of json string

[
    {
        "type": "spline",
        "name": "W dor\u0119czeniu",
        "color": "rgba(128,179,236,1)",
        "mystring": 599,
        "data": ...
    }
]

I am trying to access this json as json['W doręczeniu']['mysting'], and I get no value why is that?

Upvotes: 0

Views: 52

Answers (2)

Ryan Conaway
Ryan Conaway

Reputation: 446

The value of "W doręczeniu" is not a key, so you cannot use it to get a value. Since your json string is an array you'll have to do json[0].nameto access the first (and only) element in the array, which happens to be the object. Of course, this is assuming json is the variable you store the array into.

var json = [{"type":"spline","name":"W dor\u0119czeniu","color":"rgba(128,179,236,1)","mystring":599}];

console.log(json[0].mystring); //should give you what you want.

EDIT: To get the last element in a js array, you can simply do this:

console.log( json[json.length -1].mystring ); // same output as the previous example

'length - 1' because js arrays are indexed at 0. There's probably a million and one ways to dynamically get the array element you want, which are out of the scope of this question.

Upvotes: 0

Vincent
Vincent

Reputation: 329

You're trying to access the index "W doręczeniu" but that's not an index it's a value. Also, what you seem to have is an array of JSON objects. The [ at the start marks the array, the first element of which is your JSON object. The JSON obj begins with the { You're also trying to use a [ ], but JSON values are accessed with the dot operator. I'm not sure which index you're actually trying to access, but try something like this:

var x = json[0].mystring;

Upvotes: 1

Related Questions