Skip to content

Switch parsejson() from PSON to JSON parsing #1240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/puppet/parser/functions/parsejson.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# frozen_string_literal: true

require 'puppet/util/json'
#
# parsejson.rb
#
Expand All @@ -14,13 +15,14 @@ module Puppet::Parser::Functions

> *Note:*
The optional second argument can be used to pass a default value that will
be returned if the parsing of YAML string have failed.
be returned if the parsing of the JSON string failed or if the JSON parse
evaluated to nil.
DOC
) do |arguments|
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1

begin
PSON.load(arguments[0]) || arguments[1]
Puppet::Util::Json.load(arguments[0]) || arguments[1]
rescue StandardError => e
raise e unless arguments[1]
arguments[1]
Expand Down
14 changes: 11 additions & 3 deletions spec/functions/parsejson_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@
end

context 'with correct JSON data' do
it 'is able to parse JSON this is a null' do
is_expected.to run.with_params('null').and_return(nil)
end

it 'is able to parse JSON that is a string' do
is_expected.to run.with_params('"a string"').and_return('a string')
end

it 'is able to parse JSON data with a Hash' do
is_expected.to run.with_params('{"a":"1","b":"2"}')
.and_return('a' => '1', 'b' => '2')
Expand Down Expand Up @@ -49,16 +57,16 @@

context 'with incorrect JSON data' do
it 'raises an error with invalid JSON and no default' do
is_expected.to run.with_params('')
.and_raise_error(PSON::ParserError)
is_expected.to run.with_params('error')
.and_raise_error(Puppet::Util::Json::ParseError)
end

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

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