From bf1da3c6fbeeb6e90fe8e52289415ce370c452ac Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Wed, 9 Dec 2020 16:45:30 +0100
Subject: [PATCH] =?UTF-8?q?JSON=20output:=20fix=20logic=20in=20=E2=80=9Cva?=
 =?UTF-8?q?riable=5Fmapping=E2=80=9D=20that=20could=20lead=20to=20invalid?=
 =?UTF-8?q?=20JSON=20formatting?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Ref. dynare#1755
---
 src/DynamicModel.cc | 29 ++++++++++++++++++-----------
 1 file changed, 18 insertions(+), 11 deletions(-)

diff --git a/src/DynamicModel.cc b/src/DynamicModel.cc
index 56e74514..c4573c5a 100644
--- a/src/DynamicModel.cc
+++ b/src/DynamicModel.cc
@@ -6037,17 +6037,24 @@ void
 DynamicModel::writeJsonVariableMapping(ostream &output) const
 {
   output << R"("variable_mapping":[)" << endl;
-  int ii = 0;
-  int end_idx_map = static_cast<int>(variableMapping.size()-1);
-  for (const auto &variable : variableMapping)
-    {
-      output << R"({"name": ")" << symbol_table.getName(variable.first) << R"(", "equations":[)";
-      int it = 0;
-      int end_idx_eq = static_cast<int>(variable.second.size())-1;
-      for (const auto &equation : variable.second)
-        if (auto tmp = equation_tags.getTagValueByEqnAndKey(equation, "name"); !tmp.empty())
-          output << R"(")" << tmp << (it++ == end_idx_eq ? R"("])" : R"(", )");
-      output << (ii++ == end_idx_map ? R"(})" : R"(},)") << endl;
+  for (auto it = variableMapping.begin(); it != variableMapping.end(); ++it)
+    {
+      if (it != variableMapping.begin())
+        output << ", ";
+      auto [var, eqs] = *it;
+      output << R"({"name": ")" << symbol_table.getName(var) << R"(", "equations":[)";
+      bool first_eq = true;
+      for (auto it2 = eqs.begin(); it2 != eqs.end(); ++it2)
+        if (auto tmp = equation_tags.getTagValueByEqnAndKey(*it2, "name");
+            !tmp.empty())
+          {
+            if (first_eq)
+              first_eq = false;
+            else
+              output << ", ";
+            output << '"' << tmp << '"';
+          }
+      output << "]}" << endl;
     }
   output << "]";
 }
-- 
GitLab