如何使用Regex简化返回值?

时间:2014-06-25 13:10:04

标签: javascript regex

我使用过Imgur API并且它有效,问题是它返回带有所有参数的数据,它看起来像:

{"data":{"id":"TjJuJ29","title":null,"description":null,"datetime":1403695169,"type":"image\/png","animated":false,"width":1538,"height":839,"size":733684,"views":0,"bandwidth":0,"favorite":false,"nsfw":null,"section":null,"deletehash":"lCqsN0tKqWyJFET","link":"http:\/\/i.imgur.com\/TjJuJ29.jpg"},"success":true,"status":200}

我需要知道什么是正确的正则表达式将其转换为简单的链接URL并忘记其他参数。我正在使用Javascript。

预期输出如下: http://i.imgur.com/TjJuJ29.jpg

谢谢!

编辑:这是JSON,我的错误。

1 个答案:

答案 0 :(得分:5)

您不想使用正则表达式。

假设您的变量存储如下:

var myResult = {"data":{"id":"TjJuJ29","title":null,"description":null,"datetime":1403695169,"type":"image\/png","animated":false,"width":1538,"height":839,"size":733684,"views":0,"bandwidth":0,"favorite":false,"nsfw":null,"section":null,"deletehash":"lCqsN0tKqWyJFET","link":"http:\/\/i.imgur.com\/TjJuJ29.jpg"},"success":true,"status":200}

然后,只需使用它来获取链接:

myResult.data.link

结果似乎只是JavaScript Object 但是,如果它是JSON字符串,您可能需要先使用JSON.parse()

var myResult = JSON.parse('{"data":{"id":"TjJuJ29","title":null,"description":null,"datetime":1403695169,"type":"image\/png","animated":false,"width":1538,"height":839,"size":733684,"views":0,"bandwidth":0,"favorite":false,"nsfw":null,"section":null,"deletehash":"lCqsN0tKqWyJFET","link":"http:\/\/i.imgur.com\/TjJuJ29.jpg"},"success":true,"status":200}');