简体   繁体   English

如何预解析JSON字符串?

[英]How do I pre parse a JSON String?

I want to feed this JSON URL to another site 我想将此JSON URL馈送到另一个站点

http://naturetrek.co.uk/blog/api/get_recent_posts/ http://naturetrek.co.uk/blog/api/get_recent_posts/

But the problem is that because of the initial three <p> tags its not valid JSON, you can check this in here... 但是问题在于,由于开头的三个<p>标记无效的JSON,您可以在此处进行检查...

http://jsonlint.com/ http://jsonlint.com/

if u remove these 3 tags, it becomes valid. 如果您删除了这3个标签,它将变为有效。

We cant change the JSON string output from the Naturetrek Blog. 我们无法更改Naturetrek博客输出的JSON字符串。

In our own code we use the following.... 在我们自己的代码中,我们使用以下...。

<h2>Naturetrek BLOG</h2>
<div id="ntblog"></div>

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">

    $(document).ready(function () {

        var blogURL = "http://naturetrek.co.uk/blog/api/get_recent_posts/";

        $.getJSON(blogURL, function(info) {

            alert("here");
            var output = info.status;

            /*
            for (var i = 0; i <= info.posts.length - 1; i++) {
            output += '<li>' +
            '<a href = "' + info.posts[i].url +
            '">' + info.posts[i].title + '</a></li>';

            }
            */

            var ntblog = document.getElementById('ntblog');
            ntblog.innerHTML = output;
        });
    });
</script>

The alert never gets called, because the JSON is invalid JSON. 永远不会调用警报,因为JSON是无效的JSON。 MY QUESTION IS -- IS THERE A WAY TO PREPARSE THE JSON TO REMOVE THE THREE <p> TAGS, SOMEHOW? 我的问题是-是否可以通过某种方式准备JSON来删除三个<p>标记? OR ANOTHER WAY U CAN THINK OF? 还是您可以想到的另一种方法?

$.getJSON is just shorthand for: $ .getJSON只是以下内容的简写:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

See documentation here: http://api.jquery.com/jQuery.getJSON/ 请参阅此处的文档: http : //api.jquery.com/jQuery.getJSON/

Just use $.ajax change dataType to "html" and parse your modified JSON data in the success function with $.parseJSON 只需使用$ .ajax将dataType更改为“ html”并使用$ .parseJSON解析成功函数中的已修改JSON数据

Note: Since it seems you are doing a cross-domain request, you must use jsonp, read more here: 注意:由于您似乎正在执行跨域请求,因此必须使用jsonp,请在此处阅读更多信息:

http://learn.jquery.com/ajax/working-with-jsonp/ http://learn.jquery.com/ajax/working-with-jsonp/

You should REALLY ask them to fix their JSON... 您应该真正要求他们修复其JSON ...

In the meantime, as a patch, you should download it as HTML content, preparse it (by removing the tags) and then parse the resulting content as plain JSON. 同时,作为补丁,您应该将其下载为HTML内容,对其进行准备(通过除去标签),然后将所得内容解析为纯JSON。

But the above procedure is really a patch that should disappear when the JSON producers fixes it. 但是上述过程实际上是一个补丁,当JSON生产者对其进行修复时,该补丁应该会消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM