From 53a8ccf869aa49de7a77c8a35d89dd5aac8fa52d Mon Sep 17 00:00:00 2001 From: Sean Millichamp Date: Mon, 2 May 2022 16:20:01 -0400 Subject: [PATCH] Switch parsejson() from PSON to JSON parsing The use of PSON is deprecated and mostly removed from Puppet. Switch this function from using PSON to a real JSON parsing library via the MultiJson helper in Puppet::Util::Json. --- lib/puppet/parser/functions/parsejson.rb | 6 ++++-- spec/functions/parsejson_spec.rb | 14 +++++++++++--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/puppet/parser/functions/parsejson.rb b/lib/puppet/parser/functions/parsejson.rb index bb1992e10..8dd94e223 100644 --- a/lib/puppet/parser/functions/parsejson.rb +++ b/lib/puppet/parser/functions/parsejson.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'puppet/util/json' # # parsejson.rb # @@ -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] diff --git a/spec/functions/parsejson_spec.rb b/spec/functions/parsejson_spec.rb index bc8c2f70c..991d52e6c 100644 --- a/spec/functions/parsejson_spec.rb +++ b/spec/functions/parsejson_spec.rb @@ -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') @@ -49,8 +57,8 @@ 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 @@ -58,7 +66,7 @@ .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')