-1

I'm using jsoncpp to store information in JSON format. I now have the need to store a json string inside of another json string... In other words, I need to store a sub_item inside of an item.

Using jsoncpp to generate the JSON string, I get this...

{"id":"1","name":"Advil","sub_item":"{\"id\":\"2\",\"name\":\"Liquid Gel Advil\"}\n"}

Which works perfectly fine during runtime. However, when my program saves this information into a MySQL database (on exit) and then loads it back up when I restart the program, it loads the same JSON string from the MySQL database, but it now looks like this...

{"id":"1","name":"Advil","sub_item":"{"id":"2","name":"Liquid Gel Advil"}"}

Which is an invalid JSON string. I'm not sure why this is happening can someone please tell me what the heck is going on...

My MySQL query string reads like so:

UPDATE json_string_test SET jsonstring='{"id":"1","name":"Advil","sub_item":"{\"id\":\"2\",\"name\":\"Liquid Gel Advil\"}\n"}';
Rick
  • 353
  • 1
  • 16
  • How do you compose that `UPDATE` query, how does that code look like? – t.niese Apr 10 '18 at 06:47
  • The same way you'd store any other string in a json string. Start by not building json strings by hand and not manipulating them directly as strings. – Kevin B Apr 10 '18 at 22:23
  • @KevinB I don't, as I said I use a library called jsoncpp. I think the issue is a bug in the library, currently waiting for a response from them. – Rick Apr 11 '18 at 06:02

2 Answers2

-1

Upon further research I found out FastWriter was depreciated, and StreamWriterBuilder was the recommended writer. However, it still produced the same problem as FastWrtier....

I managed to rig a fix by doing the following...

1) Before saving to the database, I replaced ALL substrings matching \" to \\" in ONLY the child JSON string (with id 2).

2) Upon loading the JSON string, I replaced ALL substrings matching \\" to \" in ONLY the child JSON string (with id 2).

I don't understand why the heck I have to do this, so if anyone has a better solution or an explanation... I'd love to hear it.

Rick
  • 353
  • 1
  • 16
-1

I think you need to transpose your last 2 characters (assuming your posted string is verbatim). You have Advil\"}\n"} but I think you need Advil\"}\n}"

cdunn2001
  • 17,657
  • 8
  • 55
  • 45