最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing an array inside of JSON object from reviver - Stack Overflow

programmeradmin2浏览0评论

I have a JSON object formatted like {"Foo": ["B","A","R"]}

I am trying to access the values of the array like this:

var json = '{"Foo": ["B","A","R"]}';

expression = JSON.Parse(json, function(key, value){
          if(key == "Foo"){
             console.log(value.length); // logs "3"
             console.log(value[1]);     // logs "undefined"
           } 
       });

If I ask for the length of value it returns the correct length of the array, but if I ask for the value it returns undefined and I am not quite sure why.There are other values in the JSON that I am able to access just fine, but they are not arrays. Any insight would be appreciated. Thanks!

I have a JSON object formatted like {"Foo": ["B","A","R"]}

I am trying to access the values of the array like this:

var json = '{"Foo": ["B","A","R"]}';

expression = JSON.Parse(json, function(key, value){
          if(key == "Foo"){
             console.log(value.length); // logs "3"
             console.log(value[1]);     // logs "undefined"
           } 
       });

If I ask for the length of value it returns the correct length of the array, but if I ask for the value it returns undefined and I am not quite sure why.There are other values in the JSON that I am able to access just fine, but they are not arrays. Any insight would be appreciated. Thanks!

Share Improve this question edited Oct 27, 2017 at 9:13 Matthew Wilcoxson 3,6221 gold badge45 silver badges48 bronze badges asked Sep 28, 2016 at 3:08 MrPickleMrPickle 334 bronze badges 5
  • Is this your actual code? value !== Valid – Sterling Archer Commented Sep 28, 2016 at 3:12
  • You have an issue with the JSON structure var json = '{"Foo": ["B","A","R"]}'; Double quotes and single quotes are conflicting – Gary Commented Sep 28, 2016 at 3:14
  • Its not my actual code, the actual code works with the rest of the JSON values, but not the one with the array. – MrPickle Commented Sep 28, 2016 at 3:19
  • var json = '{"Foo": ["B","A","R"]}'; console.log(JSON.parse(json).Foo); – Gary Commented Sep 28, 2016 at 3:21
  • Is your objective simply to access the value in the array, or do you have some specific reason to use the second optional "reviver" parameter to JSON.parse, such as wanting to filter or transform the object while it is being parsed? – user663031 Commented Sep 28, 2016 at 4:38
Add a ment  | 

5 Answers 5

Reset to default 3

You should use JSON.parse like this:

var json = '{"Foo":["B","A","R"]}';
var object = JSON.parse(json);
// object is now and object containing the data from 'json'

var expression = object["Foo"][1]; // object["Foo"] refers to the
                                   // value with key "Foo"

(Calling JSON.parse with a callback parameter is an advanced feature for transforming the JSON object, not reading it. In almost all cases, though, you want to use it like the above code, with no callbacks.)

When the json string has arrays the reviver function is called with index, [Object] as key, value parameters .

This sniped of code that filter object properties on parse phase will be helpful:

    var json = '{"_embedded": [{"a":"A","b":"B","links": {"c":"C"}},{"a":"A2", "b":"B2","links": {"c":"C2"}}]}';
    var schemaNames=["_embedded", "a"];

    var result= JSON.parse(json, function(k, v) {
      console.log(k,v);
      if ("" === k){
        return v;
      }
      // On arrays k is a number
      else if (schemaNames.indexOf(k) > -1  || !isNaN(k)){
          return v;
      }
    });

    console.log(JSON.stringify(result));

Output: {"_embedded":[{"a":"A"},{"a":"A2"}]}

https://jsfiddle/pdorgambide/vphbmtk1/

As mentioned in another answer, if you simply want to retrieve the second element of Foo, you can do that easily enough after parsing using standard property access techniques such as obj.Foo[1].

Assuming you really want to use the optional second "reviver" parameter to JSON.parse, you need to return the value from the "reviver" callback;

expression = JSON.Parse(json, function(key, value){
  if (key == "Foo"){
     console.log(value[1]);
  } 
  return value;
  ^^^^^^^^^^^^^
});

The reason it appears you can't access value[1] but you can access value.length is (as mentioned by user663031) you don't have a return value.

The reviver function replaces one value with another, if no return is specified all functions will return undefined. The order the reviver receives the values is: first each of the values in the array separately, then the array.

In your code each value has already been replaced with "undefined", so the array has three undefined values as reported by the length. value[1] really is returning the value at position 1 but it is set to "undefined".

use this code

   var json = {'foo' : ['B', 'A', 'R']};
   $.each(json, function(key, value){if(key == 'foo'){console.log(value[1]);}});

you already have a json object so no need to parse it again.

发布评论

评论列表(0)

  1. 暂无评论