如何处理json中逗号分隔的对象? ([object Object],[object Object]) [英] How to handle comma separated objects in json? ( [object Object],[object Object] )

查看:361
本文介绍了如何处理json中逗号分隔的对象? ([object Object],[object Object])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,所以请和我一起玩。我处理的是基于JSON的Twitter API(这不是一件坏事)。

I'm new to this so please bear with me. I'm dealing with the Twitter API which relies heavily on JSON (and that's not a bad thing).

Twitter所做的就是以逗号分隔对象的形式返回一些值。这似乎是孤立的[entities]部分,枚举链接的tweet。

Something that Twitter does is return some values as comma seperated objects. This seems to be isolated to the [entities] section, which enumerates links within a tweet.

这是一个函数,我用来减少json到无序列表。注释掉这段代码的部分是我需要帮助的。

This is a function I'm using to reduce json to unordered lists. The section commented out of this code is what I need help with.

function buildULfromJSON(data){
  var items = [];

  function recurse(json){                               //declare recursion function
    items.push('<ul>');                                 // start a new <ul>

    $.each(json, function(key, val) {                   // iterate through json and test, treat vals accordingly

      if((val == '[object Object]') && (typeof val == 'object')){ // this catches nested json lists
        items.push('<li>[' + key + '] =></li>');                  // adds '[key] =>'
        recurse(val);                                             // calls recurse() to add a nested <ul>

      }else if(typeof(val)=='string'){                            // catch string values
        items.push('<li>[' + key + '] = \"' + val + '\"</li>');   // add double quotes to <li> item

      }/* else if(typeof(val) == 'object'){                      // this throws exception in jquery.js
        $.each(val, function(){                                  // when val contains [object Object],[object Object]
          items.push('<li>[' + key + '] =></li>');               // need to test for and process 
          recurse(val);                                          // comma seperated objects
        });
      } */else{
        items.push('<li>[' + key + '] = ' + val + '</li>');     // non string, non object data (null, true, 123, .etc)
      }

    });
    items.push('</ul>');                             // close </ul>
  }                                                  // end recursion function


  recurse(data);            // call recursion
  return items.join('');    // return results
}  // end buildULfromJSON()

这里是示例输出的片段其中推文包含一个主题标签,两个用户提及和三个网址。这些项目以逗号分隔的对象列表(json数据)返回。我完全失去了如何解决这个问题。你可以提供的任何方向都会非常好。

Here is snippet of example output where the tweet contains one hashtag, two user mentions, and three urls. Those items are returned as a comma seperated list of objects (json data). I'm at a complete loss how to tackle this. Any direction you guys could provide would be excellent.

注意[text]字符串。它有助于将[entities]节放在上下文中。

Note the [text] string. It helps to put the [entities] section in context.

<snippet>
[text] = "#Hashtag @PithyTwits @LuvsIt2 http://link1.com http://link2.com http://link3.com"
[retweet_count] = 0
[entities] =>
    [hashtags] =>
        [0] =>
            [text] = "Hashtag"
            [indices] = 0,8
    [user_mentions] = [object Object],[object Object]
    [urls] = [object Object],[object Object],[object Object]
[in_reply_to_screen_name] = null
[in_reply_to_status_id_str] = null
</snippet>

我现在的大问题是,我不知道如何测试这些列表, jquery.js合适。一旦我知道如何在代码中隔离这些列表,处理逗号分隔列表的字符串函数听起来不是完美的合适...任何建议都会受到欢迎。

My big issue at this point is that I don't know how to test for these lists without giving jquery.js fits. Once I do know how to isolate these lists in code, string functions for dealing with comma separated lists don't sound like the perfect fit... Any advice would be welcomed.

谢谢,

跳过

推荐答案

瘦。它是一个数组!

$。isArray(val)将返回true并标识它,它可以用$ .each()迭代;就像其他对象一样。

$.isArray(val) will return true and identify it as such, and it can be iterated with $.each(); just like other objects.

这是一个有效的对象结构,来自有效的JSON,可以通过使用PHP的json_encode()中的JSON_FORCE_OBJECT选项来避免。功能。对于我的需要,最好不要强制对象,因为我也处理整数数组,我想在一行上返回。

It is a valid object structure, from valid JSON, and can be avoided by using the JSON_FORCE_OBJECT option in PHP's json_encode(); function. For my needs it is better to not force the object because I'm also dealing with arrays of integers I want returned on a single line.

对于我的需要我改变了第一个if()在我的recusion函数中从这...

For my needs I changed the first if() in my recusion function from this...

if((val == '[object Object]') && (typeof val == 'object')){

/ p>

to this...

if((val != null) && (typeof val == 'object') &&
    ((val == '[object Object]') || (val[0] == '[object Object]'))){

这将匹配对象或对象数组,然后将它们发送回resurse();

That will match objects, or arrays of objects, then send them back to resurse();

奇怪的是,Javascript抱怨当val为null并且我们测试val [0]。我想这可能是有道理的,因为你不只是测试的价值,你也试图潜入null对象。

Oddly, Javascript complains when val is null and we test against val[0]. I guess it probably makes sense, because you aren't just testing against the value, your also trying to dive into the null object.

感谢您的关注,我想我的问题,我现在有一个帐户上Stackoverflow。这是一个双赢的结果!

Thanks for your attention, I figured out my issue, and I've now got an account on Stackoverflow. It's a win-win-win!

再次感谢。

跳过

这里是修改的buildULfromOBJ(); function ...

Here is the revised buildULfromOBJ(); function...

function buildULfromOBJ(obj){
  var fragments = [];

  //declare recursion function
  function recurse(item){
    fragments.push('<ul>'); // start a new <ul>

    $.each(item, function(key, val) {  // iterate through items.

      if((val != null) && (typeof val == 'object') &&   // catch nested objects
               ((val == '[object Object]') || (val[0] == '[object Object]'))){

        fragments.push('<li>[' + key + '] =></li>'); // add '[key] =>'
        recurse(val);            // call recurse to add a nested <ul>

      }else if(typeof(val)=='string'){  // catch strings, add double quotes

        fragments.push('<li>[' + key + '] = \"' + val + '\"</li>');

      }else if($.isArray(val)){         // catch arrays add [brackets]

        fragments.push('<li>[' + key + '] = [' + val + ']</li>');

      }else{                            // default: just print it.

        fragments.push('<li>[' + key + '] = ' + val + '</li>'); 
      }
    });
    fragments.push('</ul>'); // close </ul>
  }
  // end recursion function

  recurse(obj);            // call recursion
  return fragments.join('');    // return results
}  // end buildULfromJSON()

做出漂亮的输出,并帮助字符串和文字之间的deliniate。

The top two elses are simply to make pretty output, and help deliniate between strings and literals. They can be removed to streamline the flow.

这里是我之前发布的相同的代码段,这次正确格式化...

Here is the same snippet I posted earlier, properly formatted this time...

<snippet>
[text] = "#Hashtag @PithyTwits @LuvsIt2 http://link1.com http://link2.com http://link3.com"
[retweet_count] = 0
[entities] =>
    [hashtags] =>
        [0] =>
            [text] = "Hashtag"
            [indices] = [0,8]
    [user_mentions] =>
        [0] =>
            [indices] = [9,20]
            [screen_name] = "PithyTwits"
            [name] = "[object Object]"
            [id_str] = "258175966"
            [id] = 258175966
        [1] =>
            [indices] = [21,29]
            [screen_name] = "LuvsIt2"
            [name] = "Strictly Indifferent"
            [id_str] = "255883555"
            [id] = 255883555
    [urls] =>
        [0] =>
            [indices] = [30,46]
            [url] = "http://link1.com"
            [expanded_url] = null
        [1] =>
            [indices] = [47,63]
            [url] = "http://link2.com"
            [expanded_url] = null
        [2] =>
            [indices] = [64,80]
            [url] = "http://link3.com"
            [expanded_url] = null
[in_reply_to_screen_name] = null
</snippet>

请注意[entities] [user_mentions] [0] [name] =[object Object]我坚持,以确保字符串值不破坏代码。还要注意[indices]项。这些是我喜欢在一行上看到的数组(我得到肛门的愚蠢的东西:))

Notice that [entities][user_mentions][0][name] = "[object Object]" I stuck that in to ensure that string values don't break the code. Also notice the [indices] items. Those are the arrays I prefer to see on a single line (I get anal over the stupidest stuff :) )

再次感谢!

这篇关于如何处理json中逗号分隔的对象? ([object Object],[object Object])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆