如何处理json中逗号分隔的对象? ( [对象对象],[对象对象] )

发布于 2024-11-01 21:29:53 字数 2722 浏览 1 评论 0原文

我对此很陌生,所以请耐心等待。我正在处理严重依赖 JSON 的 Twitter API(这并不是一件坏事)。

Twitter 所做的就是以逗号分隔的对象的形式返回一些值。这似乎与 [entities] 部分隔离,该部分枚举推文中的链接。

这是我用来将 json 缩减为无序列表的函数。这段代码中注释掉的部分是我需要帮助的部分。

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 数据)返回。我完全不知道如何解决这个问题。你们能提供的任何方向都会很棒。

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

<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 拟合的情况下测试这些列表。一旦我知道如何在代码中隔离这些列表,用于处理逗号分隔列表的字符串函数听起来并不完美......任何建议都会受到欢迎。

谢谢你,

跳过

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).

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.

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()

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.

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>

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.

Thank You,

Skip

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ペ泪落弦音 2024-11-08 21:29:53

好吧,这里是瘦子。这是一个数组!

$.isArray(val) 将返回 true 并对其进行标识,并且可以使用 $.each() 进行迭代;就像其他物体一样。

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

根据我的需要,我将递归函数中的第一个 if() 从 this... 更改

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

为 this...

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

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

奇怪的是,当 val 为 null 时,Javascript 会抱怨,而我们则针对 val[0] 进行测试。我想这可能是有道理的,因为您不仅测试该值,还尝试深入研究 null 对象。

感谢您的关注,我已经解决了我的问题,现在我在 Stackoverflow 上有了一个帐户。这是双赢!

再次感谢。

跳过


这里是修改后的 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()

上面的两个 else 只是为了生成漂亮的输出,并帮助区分字符串和文字。可以将它们移除以简化流程。

这是我之前发布的相同片段,这次格式正确...

<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]" 我将其插入以确保字符串值不会中断代码。另请注意 [index] 项。这些是我更喜欢在一行中看到的数组(我对最愚蠢的东西感到厌烦:))

再次感谢!

OK, here's the skinny. It's an Array!

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

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.

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

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

to this...

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

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

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.

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

Thanks again.

Skip


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()

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>

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 :) )

Thanks again!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文