replacing a placeholder in a html file with 1-n specific values defined in a config.json using shellscript [closed]

浪子不回头ぞ 提交于 2021-02-04 21:58:23

问题


The Problem:

I need to replace a placeholder (__PLACEHOLDER__) in a html file index.html with 1-n specific values defined in a config.json file.

what I tried:

replacing the placeholder inside index.html with new content: echo "${html//__PLACEHOLDER__/$replace}" > index.html

getting the values from json (not working): replace=$(sed 's/.*"host": "\(.*\)"/\1/g;d;t' config.json) this is not a good approach and currently does not return the desired values

So i know how to replace the value in the html file, but i dont know how to get the values i need into a variable before that. I already tried it with sed or perl, with sed however the issue is its not cross platform compatible which it need to be.

config.json:

{
    "xxxx": {
        "description": "xxxxx",
        "value": {
            "to": [
                "xxxxxx"
            ]
        }
    },
    "xxxx": {
        "description": "xxx",
        "value": "xxxxxx"
    },
    "API": {
        "description": "xxxxxxxxx",
        "value": {
            "default": {
                "host": "VALUE I WANT"
            },
            "auth": {
                "host": "VALUE I WANT"
            }
        }
    },
}

default and auth are only some possible values it could be 1-n hosts.

in the end i would like a variable with all the hosts as strings: host1 host2 host3

info: we cannot use any 3rd party tools which are not usually present on systems & the index.html file is of no interest, we just replace the placeholder value.

I appreciate your help


回答1:


we cannot use any 3rd party tools which are not usually present on systems

Given that we don't know what "systems" you're using, this isn't a very useful restriction to tell us about.

Perl has several JSON parsers available and since Perl 5.14 (which was released in May 2011) one of them (JSON::PP) has been part of the standard Perl distribution. So if you have a version of Perl that was released in the last nine years, then the task of reading the JSON file into a variable is trivial.

#!/user/bin/perl

use strict;
use warnings;
use feature 'say';

use JSON::PP;
use Data::Dumper;

open my $json_fh, '<', 'config.json' or die $!;

my $json = do { local $/; <$json_fh> };

my $config = JSON::PP->new->decode($json);

# Now you have your JSON in a Perl data structure
say Dumper $config;

# You can also access individual values
say $config->{xxxx}{description};
say $config->{API}{value}{default}{host};


来源:https://stackoverflow.com/questions/62343454/replacing-a-placeholder-in-a-html-file-with-1-n-specific-values-defined-in-a-con

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!