简体   繁体   English

如何正确地将XML字符串化以作为CURL命令的一部分放入JSON主体

[英]How to properly stringify XML to put in JSON body as part of CURL command

I'd like to add an XML file to my JSON request body in a CURL command. 我想通过CURL命令将XML文件添加到JSON请求正文中。 This is what I have right now 这就是我现在所拥有的

data=$(cat testdata.xml)
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ "data": ''"$(echo $data)"''}' 'http://...'

However this sends { data: '$(echo $data)' } } instead of actually fetching the file. 但是,这发送{ data: '$(echo $data)' } }而不是实际获取文件。

If I take out the outer single quotes around $(echo $data) like this: 如果我像这样取出$(echo $ data)周围的外部单引号:

data=$(cat testdata.xml)
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ "data": '"$(echo $data)"'}' 'http://...'

Then I encounter error Unexpected token < in JSON at position 10 然后我在位置10的JSON中遇到错误Unexpected token <

because the server is reading 因为服务器正在读取

'{ "data": <?xml version="1.0" encoding="UTF-8"?> - <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don\'t forget me this weekend!</body> </note>}',

How do I fix this? 我该如何解决? Note that I do NOT want to convert to JSON first. 请注意,我不想先转换为JSON。 I only want to send the stringified xml file in body. 我只想在正文中发送字符串化的xml文件。

As always, use jq to generate properly-escaped JSON in bash. 与往常一样,使用jq在bash中生成正确转义的JSON。

data=$(jq -Rs '{ "data": . }' <testdata.xml)
curl -X POST \
     --header 'Content-Type: application/json' \
     --header 'Accept: application/json' \
     -d "$data" \
     "$url"

If you don't have jq installed, you can use Python for the job, substituting the following for the line that used jq : 如果您尚未安装jq ,则可以使用Python进行作业,将以下内容替换为使用jq的行:

data=$(python -c 'import json, sys; json.dump({"data": sys.stdin.read()}, sys.stdout)' <testdata.xml)

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

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