Appending Key->Value with an existing JSON Data

Published 6 months ago by abudo

On a table column, i can save a json data in the format

{"at_quest": ["1.1"], "quest_1.1_score": "67", "quest_1.1_passed": "2018-03-20 09:48:47.886849"}

I need to update this data in the same format only some characters needs to change on subsequent updates i.e

 {"at_quest": ["1.1"], "quest_1.1_score": "67", "quest_1.1_passed" : "2018-03-20 09:48:47.886849","at_quest": ["1.2"], "quest_1.2_score": "67", "quest_1.2_passed" : "2018-03-20 09:48:47.886849"}

My code

$obj = DB::table('table')->where('user_id',$userIid)->where('product_id',$productId)->value('history');



      if($obj){
        $data[]=json_decode($obj);
        $at = Carbon::now();
        $data["at_quest"]=$questId;
        $data["quest_".$questId."_score"] = $percentageScore;
        $data["quest_".$questId."_passed"] =  $at;
        $json_data = json_encode($data);
        
        UserTrainingHistory::where('user_id', $userIid)
         ->where('product_id', $productId)
         ->update(['history' => $json_data]);
         dd('we will update the quest');
      }else{
        $data=[];
        $at = Carbon::now();
        $data["at_quest"]=$questId;
        $data["quest_".$questId."_score"] = $percentageScore;
        $data["quest_".$questId."_passed"] =  $at;
        $data1 = json_encode($data);

        $UserTraininghHstory = new UserTrainingHistory;
        $UserTraininghHstory->user_id = $userIid;
        $UserTraininghHstory->product_id = $productId;
        $UserTraininghHstory->history = $data1;

        $UserTraininghHstory->save();
        dd($UserTraininghHstory);
      }

what i got stored in database is this, which is wrong

{"0": {"0": {"at_quest": "1.1", "quest_1.1_score": "100", "quest_1.1_passed": {"date": "2018-03-21 07:16:30.099540", "timezone": "UTC", "timezone_type": 3}}, "at_quest": "1.2", "quest_1.2_score": "67", "quest_1.2_passed": {"date": "2018-03-21 07:17:38.727736", "timezone": "UTC", "timezone_type": 3}}, "at_quest": "1.3", "quest_1.3_score": "100", "quest_1.3_passed": {"date": "2018-03-21 09:58:01.707335", "timezone": "UTC", "timezone_type": 3}}
Cinek
Cinek
6 months ago (24,960 XP)
 {"at_quest": ["1.1"], "quest_1.1_score": "67", "quest_1.1_passed" : "2018-03-20 09:48:47.886849","at_quest": ["1.2"], "quest_1.2_score": "67", "quest_1.2_passed" : "2018-03-20 09:48:47.886849"}

It's not valid JSON. You have 2 same property names.

abudo
abudo
6 months ago (31,900 XP)

@Cinek it serves the purpose. attributes are different

Dry7
Dry7
6 months ago (152,030 XP)

Please sign in or create an account to participate in this conversation.