从字符串中过滤出JSON,以便使用php进一步处理

问题描述 投票:0回答:1

在我的应用程序中,我调用了一个返回JSON的API,遗憾的是,这个JSON被一个包含HTML元素的字符串包围

示例返回

{"code":[{"name":"code","text":null,"attributes":[],"children":[]}],"message":[{"name":"message","text":"An error occurred while processing this request.","attributes":[],"children":[]}],"innererror":[{"name":"innererror","text":null,"attributes":[],"children":{"message":[{"name":"message","text":"Entiteit: Validatiefout","attributes":[],"children":[]}],"type":[{"name":"type","text":"System.Exception","attributes":[],"children":[]}],"stacktrace":[{"name":"stacktrace","text":"at Exact.Services.REST.DataServiceUpdateProvider.ErrorException(FaultException`1 fe, IExactRestConnection connection)\r\n   at Exact.Services.REST.DataServiceUpdateProvider._Closure$__6._Closure$__7._Lambda$__6()\r\n   at Exact.Services.REST.DataServiceUpdateProvider.SaveChanges()\r\n   at System.Data.Services.DataService`1.HandleNonBatchRequest(RequestDescription description)\r\n   at System.Data.Services.DataService`1.HandleRequest()","attributes":[],"children":[]}],"internalexception":[{"name":"internalexception","text":null,"attributes":[],"children":{"message":[{"name":"message","text":"Property: Ongeldige referentie, Message: Artikelcode: 'EY05547'","attributes":[],"children":[]}],"type":[{"name":"type","text":"System.Exception","attributes":[],"children":[]}],"stacktrace":[{"name":"stacktrace","text":null,"attributes":[],"children":[]}]}}]}}]}<div class="debugmsgs"><div class="debugtitle"><span id="debugtitlename">Debugger</span> | <a id="debugtitlename2">Autofill</a> <div class="debugtitle-link"><a id="debugtitle-a" href="#" onclick="toggleDebug(); return false;">inklappen</a></div></div><div class="debugerrors"><div class="debugerror debugerror-php">Undefined index: content<br /><em>C:\laragon\www\b-</div><div class="debugerror debugerror-php">Undefined index: content<br /><em></em><br /></div></div></div>

正如你在json中看到的那样:

:[],"children":[]}]}}]}}]}<div class="debugmsgs">

Html被附加到字符串,这使我无法进行JSON解码。因此,我需要删除HTML,或提取JSON。

我想要做的是将返回的字符串中的JSON放入变量中以进行进一步处理。

到目前为止,如果试图使用正则表达式执行此操作:{(?:[^ {}] |())*}但我似乎无法做到正确。

php json regex
1个回答
1
投票

看起来你的json格式不正确,因为某种调试代码与输出一起产生,解决这个问题的正确方法是找出导致下面的调试消息出来的原因

<div class="debugmsgs"><div class="debugtitle"><span id="debugtitlename">Debugger</span> | <a id="debugtitlename2">Autofill</a> <div class="debugtitle-link"><a id="debugtitle-a" href="#" onclick="toggleDebug(); return false;">inklappen</a></div></div><div class="debugerrors"><div class="debugerror debugerror-php">Undefined index: content<br /><em>C:\laragon\www\b-</div><div class="debugerror debugerror-php">Undefined index: content<br /><em></em><br /></div></div></div>

如果你无法摆脱输出,你可以使用的其他方式是PHP爆炸删除不需要的字符串,如下所示:

$string = explode("<div", $api_output); //break the string into array using the '<div' as breaking point
$result = json_decode($string[0]); //decoded version of the json output
© www.soinside.com 2019 - 2024. All rights reserved.