json - 从 txt 文件中提取特定字符串并将提取的字符串复制到批处理文件中的 json 文件中
问题描述
我有文本文件 abc.txt,其内容为:
abc.txt:
{"nature":"calm","trees":"uprooted from the main area","name":"usdbuebcowecy821nkwh29y2bnso3ns389ye3wnsiwsn9usj","enrolled":"not yet"}
我需要从 abc.txt 中提取与名称关联的字符串“usdbuebcowecy821nkwh29y2bnso3ns389ye3wnsiwsn9usj”。与 name 关联的字符串会有所不同,并且不是静态的。因此,无论字符串与 name 相关联,都必须在 sample.json 文件中提取和更新。
示例.json:
{
"requisite":{
"name": "usdbuebcowecy821nkwh29y2bnso3ns389ye3wnsiwsn9usj"
},
"land": {
"key": "890"
}
}
Sample.json 文件名键应使用从 abc.txt 名称字段中提取的适当名称进行更新。
我尝试下面的代码片段来提取名称字段 abc.txt 文件:
For /f "tokens=1 delims=:" %%j in ('dir /b /s "C:\abc.txt" ^|findstr /I ""name":"') do echo "%%j"
echo name is: %%j
但是循环不搜索名称字符串,我坚持继续进行。我是批处理脚本的新手。谁能帮我吗?
解决方案
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q64985945.txt"
:: Read sourcefile to LINE
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO SET "line=%%a"
:: Change each { } and : to comma
SET "line=%line:{=,%"
SET "line=%line:}=,%"
SET "line=%line::=,%"
:: ensure NAME is not defined
SET "name="
:: process LINE
:: set NAME when the string `name` is detected, use that flag to set NAME to the value following.
:: Note that LINE will not contain {:}, so any of these values can be used as a flag to detect
:: `name` as the last value.
FOR %%a IN (%line%) DO IF DEFINED name (SET "name=%%~a"&GOTO done ) ELSE IF /i "%%~a"=="name" SET "name=:"
:noname
ECHO No name value found
GOTO :eof
:done
SET name
GOTO :EOF
您需要更改设置sourcedir
以适应您的情况。该清单使用适合我的系统的设置。
我使用了一个名为q64985945.txt
包含您的数据的文件进行测试。
usebackq
仅需要该选项,因为我选择在源文件名周围添加引号。
不幸的是,您仍然使 JSON 文本更加神秘。您发布的示例并没有告诉我们很多事情 - 是否第一次出现name
是您需要的,或者是否有其他条件决定name
要选择哪个特定值。例如,您的原始样本不包括嵌套的大括号对。在设计解决方案方面都非常重要......
推荐阅读
- javascript - 在 Laravel 中将数据从 Blade 传递到模态
- html - 我如何使用 1 个标签来加粗多个单词?例如在下面的文本中
- ssh - 如何在服务器上登录用户并运行给定 Kerberos 票证的进程
- ios - 请求 Alamofire
- android - 没有“RECEIVE_BOOT_COMPLETED”,绑定 Jar 中的服务不会出现
- c# - 线程池 + 轮询 C# .Net 3.5
- php - PHP - 我可以使用 CodeIgniter 框架为页面设置静态 ID/密码吗?
- bash - 执行命令是 bash 并为其输出提取数据
- docker - 如何在 docker-compose.yml 中运行 php-fpm?
- dart - 如何在 EventChannel.listen 的回调 onEvent 中显示 SnackBar