gpt4 book ai didi

regex - 如何在不使用 json 库和 json 解析器的情况下解析 json 文件

转载 作者:行者123 更新时间:2023-12-05 08:42:36 25 4
gpt4 key购买 nike

下面是输入和输出的详细信息

Input : This is just a sample input and real input is huge and is just in a single line

[{"mnemonic":"PT.IA1","ID":"000628"},  {"mnemonic":"EOR.1","ID":"000703"}]

code : I'm trying to read the file by setting the delimiter as }, so that I get each value,but as its a single line file, its printing everything at one, how do I parse this line by setting a delimiter to this line , is split function enough to do this job ?

our $conf =
{
chunk_separator => '\{,',
}
open( FH, "Etot_Data.txt" ) or die $!;
while ( my $chunk = <FH> ){
my $sections = [ split $conf->{chunk_separator}, $chunk ]
print "$chunk\n";
}

Output

我想从每个值中选择“ID”并在前面添加“abc”。对它最终字符串看起来像 abc.000628 或 abc.000703 并将其保存在哈希中除了 json 字符串中的 ID 之外,不需要其他值是否可以将json文件当成普通文件来读取并对其进行操作。我没有 json 解析器,也没有使用它的选项

感谢帮助

最佳答案

如果您不能安装任何外部模块,您肯定可以包含它...

在脚本所在的同一目录中创建一个 JSON 目录,然后复制 JSON::PP 的内容模块,并将其放入刚刚创建的 JSON 目录中的 PP.pm 文件中。然后,在您的脚本中,将当前工作目录添加为库目录:use lib '.';use JSON::PP;

use warnings;
use strict;

use lib '.';

use JSON::PP qw(decode_json);

my $json;

{
local $/;
open my $fh, '<', 'file.json' or die $!;
$json = <$fh>;
}

my $perl = decode_json $json;

for (@$perl){
my $id = 'abc.' . $_->{ID};
print "$id\n";
}

输出:

abc.000628
abc.000703

如果您需要隐藏您已经创建了一个额外模块的事实,只需稍作修改,您可以对该模块进行一些更改,并将其直接包含在脚本本身中。

请注意,JSON::PP 在 v5.14+ 的 Perl 核心中。 OP 在评论中表示他们在 5.10 上。

关于regex - 如何在不使用 json 库和 json 解析器的情况下解析 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39594276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com