From 8250113e0ace36aa1ebea06c5a241eca6882f7d4 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

(manually cherry picked from commit bf1da3c6fbeeb6e90fe8e52289415ce370c452ac)
---
 src/DynamicModel.cc | 26 ++++++++++++++++----------
 1 file changed, 16 insertions(+), 10 deletions(-)

diff --git a/src/DynamicModel.cc b/src/DynamicModel.cc
index 75f272f8..2b9e3efa 100644
--- a/src/DynamicModel.cc
+++ b/src/DynamicModel.cc
@@ -6895,18 +6895,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)
+  for (auto it = variableMapping.begin(); it != variableMapping.end(); ++it)
     {
-      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 (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)
         for (const auto &equation_tag : equation_tags)
-          if (equation_tag.first == equation && equation_tag.second.first == "name")
-            output << R"(")" << equation_tag.second.second << (it++ == end_idx_eq ? R"("])" : R"(", )");
-      output << (ii++ == end_idx_map ? R"(})" : R"(},)") << endl;
+          if (equation_tag.first == *it2 && equation_tag.second.first == "name")
+            {
+              if (first_eq)
+                first_eq = false;
+              else
+                output << ", ";
+              output << '"' << equation_tag.second.second << '"';
+            }
+      output << "]}" << endl;
     }
   output << "]";
 }
-- 
GitLab