【问题标题】:Json returns every character as a separate object?Json将每个字符作为单独的对象返回?
【发布时间】:2011-01-31 20:12:57
【问题描述】:

我有一个使用 JSON API 插件从 wordpress 加载的 json 对象。当我加载 json 对象并尝试注销它的各个部分时,它似乎将每个字符都视为自己的对象,因此循环返回了几千个对象,其中包含单个字符的项目。这是我第一次使用 json,所以如果我在这里遗漏了一个步骤,请注意。这是我目前使用的代码。

function getProjInfo(theId){ 
    $.ajax({// calling the ajax object of jquery
        type: "GET",// we are going to be getting info from this data source
        url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
        dataType: "application/json",
        success: function(data){
        parseJson(data);
    }, // what happens when it is successful at loading the XML 
    error: function(){
        alert("error");
    }   
    });

}//end of the function

function parseJson(inData){
    postInfo = inData;
    $.each(postInfo, function(index, value){
    console.log(this);
});

}

json 看起来像这样:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
@987654328 @
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n","excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
@987654353 @
"comment_count": 0,
"comment_status": "open"
}

所以基本上不是给我“status”作为键和“ok”作为值,而是将“s”作为索引为 0 的对象,该对象对于 json 中的每个字符都具有“s”值目的。对此问题的任何帮助将不胜感激。

【问题讨论】:

  • 仅供参考 - 如果您想显示类似 JSON 内容的代码片段,请将其粘贴到编辑框中,选择它,然后点击编辑框上方的“{}”小部件。
  • 谢谢,我会记住的

标签: javascript jquery json wordpress


【解决方案1】:

您需要在 $.ajax() 请求中设置 dataType:json,以便 jQuery 将 JSON 格式的字符串转换为 JavaScript 对象,以便您进行处理。您当前使用的 application/json 是一种 mime 类型,在 jQuery 请求中该字段的值无效。

【讨论】:

  • 非常感谢,在之前的获取 json 信息加载的方法失败后,我一定把它留在了那里:)
【解决方案2】:

在您的情况下,您甚至可以尝试 data = eval(data) ,这个 javascript 语句应该将您的字符串转换为 json 对象。

【讨论】:

    【解决方案3】:

    使用Jquery函数:

    data = $.parseJSON(data);
    

    在使用 $.each 之前。

    【讨论】:

      【解决方案4】:

      我在 AngularJS 应用程序中解决该问题的方法是将来自服务器的响应(我使用的是 Node Express)作为 JavaScript 对象而不是字符串发送。没有其他东西对我有用。

      var response = {};
      response.error = "Error message";
      res.send(response);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-24
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-20
        • 1970-01-01
        • 2019-07-10
        • 1970-01-01
        相关资源
        最近更新 更多