Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1408
  • Last Modified:

Add row to JSON file

I need to know how i can add a row to an existing JSON file, using PHP/Jquery.

My JSON file look's as folows (data.json):

{
"komp": [
{ "mail1":"xx@xx.xx" , "name1":"John" , "name2":"Dow" }
]
}

Open in new window

0
kbnewgear
Asked:
kbnewgear
  • 3
1 Solution
 
Ray PaseurCommented:
Typically the new information would be added to an object, then the JSON string would be created from the object.  I'll see if I can show you a PHP example.
0
 
Ray PaseurCommented:
Please see http://www.laprbass.com/RAY_temp_kbnewgear.php

<?php // RAY_temp_kbnewgear.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28360318.html
// REF http://www.json.org/

// THE EXISTING JSON STRING
$jso = <<<EOD
{
"komp": [
{ "mail1":"xx@xx.xx" , "name1":"John" , "name2":"Dow" }
]
}
EOD;

// MAKE AN OBJECT
$obj = json_decode($jso);
if (!$obj) trigger_error('JSON FAIL: ' .  json_last_error(), E_USER_ERROR);

// SHOW THE ORIGINAL OBJECT
echo '<pre>';
print_r($obj);
echo PHP_EOL;

// CREATE SOME NEW DATA TO APPEND TO THE komp ARRAY
$new = new StdClass;
$new->mail1 = 'Ray.P@Gmail.com';
$new->name1 = 'Ray';
$new->name2 = 'Paseur';

// INJECT SOME DATA INTO THE OBJECT
$obj->komp[] = $new;

// SHOW THE MODIFIED OBJECT
print_r($obj);

// RENDER THE NEW JSON STRING
echo json_encode($obj);

Open in new window

0
 
Ray PaseurCommented:
@kbnewgear: I see you are relatively new to Experts-Exchange and it appears that you may not understand the community norms and the grading guidelines.  The expected and default grade is "A" and anything less than an "A" should have an explanation of the deficiency.  Since you got a tested and working code sample that showed exactly how to do what you want, and since you didn't even post an acknowledgement, I'd like to ask for your explanation of the marked down grade now.

For your reference, the grading guidelines are shown here:
http://support.experts-exchange.com/customer/portal/articles/481419

Please let us hear back from you, thanks. ~Ray
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now