-2

I want to know how to add new data in json file array

i am new to json.

want to add data from php or html input.

[
{
    "id":1,
    "name":"abc",
    "value":"abcd"
},
{
    "id":2,
    "name":"Kiss",
    "value":"Kiss"
}
{
    "id":3,
    "name":"efgh",
    "value":"efgh"
}
]

How can i add forth item of array in json file with php or html input

please help me with example ,

thanks

user2380033
  • 1
  • 1
  • 1
  • 2
  • 2
    What about decoding, modify the array and then encoding back? – Fabio Jun 03 '13 at 18:03
  • Check out this question,possible duplicate: http://stackoverflow.com/questions/1745052/add-new-data-into-php-json-string – Jose Vega Jun 03 '13 at 18:04
  • [i have posted answer to ur problem here] http://stackoverflow.com/questions/3921520/writing-json-object-to-json-file-on-server/39091183#39091183 – sudheer Aug 23 '16 at 02:16

1 Answers1

10

Firstly, I'll just note the JSON you showed isn't valid (it's missing a comma :P), but here is the answer:

You have to load it in.

$data = json_decode($json, true);

($json should be the JSON, and true is to specify to decode as associative array where necessary)

then add your element,

$data[] = array('id'=>4, 'name'=>'abcdef', 'value'=>'abcdefg');

and then you can recode it as JSON

$json = json_encode($data);
  • can you please help me ? can you give me example with php file , i actually dont know how to add with php also. – user2380033 Jun 04 '13 at 03:41