Skip to content

Commit 1306ed5

Browse files
authored
Merge pull request #1240 from seanmil/parsejson_use_json
Switch parsejson() from PSON to JSON parsing
2 parents 92fc20b + 53a8ccf commit 1306ed5

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

lib/puppet/parser/functions/parsejson.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# frozen_string_literal: true
22

3+
require 'puppet/util/json'
34
#
45
# parsejson.rb
56
#
@@ -14,13 +15,14 @@ module Puppet::Parser::Functions
1415
1516
> *Note:*
1617
The optional second argument can be used to pass a default value that will
17-
be returned if the parsing of YAML string have failed.
18+
be returned if the parsing of the JSON string failed or if the JSON parse
19+
evaluated to nil.
1820
DOC
1921
) do |arguments|
2022
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1
2123

2224
begin
23-
PSON.load(arguments[0]) || arguments[1]
25+
Puppet::Util::Json.load(arguments[0]) || arguments[1]
2426
rescue StandardError => e
2527
raise e unless arguments[1]
2628
arguments[1]

spec/functions/parsejson_spec.rb

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@
1313
end
1414

1515
context 'with correct JSON data' do
16+
it 'is able to parse JSON this is a null' do
17+
is_expected.to run.with_params('null').and_return(nil)
18+
end
19+
20+
it 'is able to parse JSON that is a string' do
21+
is_expected.to run.with_params('"a string"').and_return('a string')
22+
end
23+
1624
it 'is able to parse JSON data with a Hash' do
1725
is_expected.to run.with_params('{"a":"1","b":"2"}')
1826
.and_return('a' => '1', 'b' => '2')
@@ -49,16 +57,16 @@
4957

5058
context 'with incorrect JSON data' do
5159
it 'raises an error with invalid JSON and no default' do
52-
is_expected.to run.with_params('')
53-
.and_raise_error(PSON::ParserError)
60+
is_expected.to run.with_params('error')
61+
.and_raise_error(Puppet::Util::Json::ParseError)
5462
end
5563

5664
it 'supports a structure for a default value' do
5765
is_expected.to run.with_params('', 'a' => '1')
5866
.and_return('a' => '1')
5967
end
6068

61-
['', 1, 1.2, nil, true, false, [], {}, :yaml].each do |value|
69+
[1, 1.2, nil, true, false, [], {}, :yaml].each do |value|
6270
it "returns the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do
6371
is_expected.to run.with_params(value, 'default_value')
6472
.and_return('default_value')

0 commit comments

Comments
 (0)