在写入文件之前格式化 curl 输出 [英] format curl output before writing to file

查看:39
本文介绍了在写入文件之前格式化 curl 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 curl(7.39.0) 调用 REST Web 服务并将响应写入 .json 文件.

I am using curl(7.39.0) to call a REST webservice and write the response to a .json file.

我是这样称呼它的

curl -L-X POST -b cookies.txt -H "Content-Type: application/json" http://localhost:7001/web/service/url -d {"param1":"value1"} -o "C:outputserviceName.json" 

响应被写入输出文件,但没有格式化.

The response is written to the output file, but, without formatting.

{"status": "success","user": "name", "regId": "14420","subscriber": [{"memberFor":"3 years","lastLogin":"2 days ago"}]}

我的问题是:

a/ 有没有办法在将 json 响应写入输出文件(如下所示)之前对其进行格式化?

a/ Is there a way to format the json response before writing it to the output file(like below)?

{
        "status": "success",
        "user": "name",
        "regId": "14420"
        "subscriber": [
            {
                "memberFor":"3 years",
                "lastLogin":"2 days ago"     
            }
        ]
    }

b/ 如果无法通过 cURL 进行格式化,我希望编写一个简单的批处理文件来自动打开 json 输出文件并应用格式化.像

b/ If formatting is not possible via cURL, I wish to write a simple batch file to automatically open the json output file and apply formatting. Something like

@echo off
cls
"C:Program FilesNotepad++
otepad++"   "C:outputserviceName.json" 
pause

MS-BATCH 中是否有可用的标志/选项来实现这一点?

Are there any flags/options available in MS-BATCH to achieve this?

谢谢

推荐答案

我找到了一个使用 htmlfile COM 对象的解决方案,它应该提供最快的性能(至少一次运行)并且不需要互联网连接.请参阅此答案中的最后一个解决方案.

I found a solution using the htmlfile COM object, which should offer the fastest performance (at least for a single run) and does not require an Internet connection. See the last solution in this answer.

因为您使用 [batch-file] 标签标记了这个问题,并且因为我发现这个挑战很有趣,所以我编写了一个混合批处理 + JScript 脚本来美化您的 JSON.由于 JScript 5.7 本身不支持 JSON 对象,因此此脚本使用外部 json2.js,如果是则通过 XHR 下载尚未下载.从那里,只需调用 JavaScript 熟悉的 JSON.stringify() 方法及其美化选项即可.

Because you tagged this question with the [batch-file] tag, and because I found the challenge interesting, I wrote a hybrid batch + JScript script that'll beautify your JSON. Since JScript 5.7 doesn't natively support the JSON object, this script uses an external json2.js, downloading it via XHR if it's not already been downloaded. From there, it's a simple matter of calling JavaScript's familiar JSON.stringify() method with its beautify options.

语法:

json_generator | batfile.bat
    -or-
batfile.bat < jsonfile.json

示例用法:

beautify.bat < "C:outputserviceName.json" > "C:outputeautified.json"

这会导致以下内容被保存为 beautified.json:

This results in the following being saved as beautified.json:

{  
        "status": "success",
        "user": "name",
        "regId": "14420",
        "subscriber": [
                {
                        "memberFor": "3 years",
                        "lastLogin": "2 days ago"
                }
        ]
}

代码:

@if (@CodeSection == @Batch) @then

@echo off & setlocal

cscript /nologo /e:JScript "%~f0"
goto :EOF

@end // end Batch / begin JScript hybrid chimera

var xObj = WSH.CreateObject('Microsoft.XMLHTTP'),
    fso = WSH.CreateObject('Scripting.FileSystemObject'),
    temp = WSH.CreateObject('WScript.Shell').Environment('Process')('temp'),
    j2lib = 'https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js',
    json = WSH.StdIn.ReadAll();

if (fso.FileExists(temp + '\json2.js')) {
    j2lib = fso.OpenTextFile(temp + '\json2.js', 1);
    eval(j2lib.ReadAll());
    j2lib.Close();
}
else {
    with (xObj) {
        open("GET", j2lib, true);
        setRequestHeader('User-Agent', 'XMLHTTP/1.0');
        send('');
    }

    while (xObj.readyState != 4) WSH.Sleep(50);
    eval(xObj.responseText);
    j2lib = fso.CreateTextFile(temp + '\json2.js', true);
    j2lib.Write(xObj.responseText);
    j2lib.Close();
}

WSH.Echo(JSON.stringify(JSON.parse(json), null, '	'));

<小时>

这是另一个使用相同语法的解决方案,不需要下载 json2.js.它通过不可见地启动 Internet Explorer、调用 IE 的内置 JSON 方法,然后再次静默关闭 IE 来避免这种情况.这很可能会比上述方法慢,并且可能会根据机器安全策略被阻止;但它确实具有在没有 Internet 连接的情况下工作的优势.


Here's another solution using the same syntax that does not require downloading json2.js. It avoids this by launching Internet Explorer invisibly, calling IE's built-in JSON methods, then silently closing IE again. This is most likely going to be slower than the method above, and it could be blocked depending on machine security policies; but it does have the advantage of working without an Internet connection.

@if (@CodeSection == @Batch) @then

@echo off & setlocal

cscript /nologo /e:JScript "%~f0"
goto :EOF

@end // end Batch / begin JScript hybrid chimera

var IE = WSH.CreateObject('InternetExplorer.Application'),
    json = WSH.StdIn.ReadAll();

IE.Visible = 0;
IE.Navigate('about:blank');
while (IE.Busy || IE.ReadyState != 4) WSH.Sleep(25);

var JSON = IE.document.parentWindow.JSON,
    pretty = JSON.stringify(JSON.parse(json), null, "	");

WSH.Echo(pretty);

IE.Quit();
try { while (IE && IE.Busy) WSH.Sleep(25); }
catch(e) {}

<小时>

这里还有一个解决方案,这次使用的是批处理/HTA 混合.有一个 <meta> 标签强制 HTA 解释器兼容 IE9,因此包括支持 JSON 方法.这比 IE 方法更快,但并非完全不可见.HTA 窗口在屏幕上闪烁片刻,然后自行关闭.


Here's one more solution, this time using a batch / HTA hybrid. There's a <meta> tag forcing the HTA interpreter into IE9 compatibility, thus including support for JSON methods. This is faster than the IE method, but isn't completely invisible. The HTA window flashes on the screen for an instant, then closes itself.

<!-- : batch portion

@echo off & setlocal

rem // The for /f loop forces mshta to communicate with stdout
rem // as a console script host.  Without for /f, attempting
rem // to write to stdout results in an invalid handle error.
for /f "delims=" %%I in ('mshta.exe "%~f0"') do echo(%%I
goto :EOF

end batch / begin HTA : -->

<meta http-equiv="x-ua-compatible" content="IE=9" />
<script>
var fso = new ActiveXObject('Scripting.FileSystemObject'),
    stdin = fso.GetStandardStream(0),
    stdout = fso.GetStandardStream(1),
    json = stdin.ReadAll(),
    pretty = JSON.stringify(JSON.parse(json), null, '	');

close(stdout.Write(pretty));
</script>

<小时>

我认为最好的解决方案是使用 缺乏文档的 htmlfile COM 对象.使用与 <meta> 标记相同的技巧来强制它与 IE9 兼容,如上面的 HTA 解决方案所示,htmlfile COM 对象提供对 JSON 方法的本机支持无需下载库,也无需派生额外的窗口化帮助应用程序.它只是加载一个 dll.


The best solution I think is to use the scantily-documented htmlfile COM object. Using the same trick with a <meta> tag to force it into IE9 compatibility as was demonstrated with the HTA solution above, the htmlfile COM object offers native support for JSON methods without requiring a library download, and without forking an additional windowed helper application. It just loads a dll.

@if (@CodeSection == @Batch) @then

@echo off & setlocal

cscript /nologo /e:JScript "%~f0"
goto :EOF

@end // end batch / begin JScript hybrid chimera

var htmlfile = WSH.CreateObject('htmlfile'),
    json = WSH.StdIn.ReadAll();

htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');

var JSON = htmlfile.parentWindow.JSON,
    pretty = JSON.stringify(JSON.parse(json), null, '	');

htmlfile.close(WSH.Echo(pretty));

这篇关于在写入文件之前格式化 curl 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆