How to Add Item to the JSON File Formatted Array

how to add item to the json file formatted array

Just decode your json string and then use array push

$tempArray = json_decode($jsonstring, true);
array_push($tempArray, $your_data);

For your case

    $str = '{ 

"players":[
{

"name":"Moldova",
"image":"/Images/Moldova.jpg",
"roll_over_image":"tank.jpg"
},
{

"name":"Georgia",
"image":"/Images/georgia.gif",
"roll_over_image":"tank.jpg"
} ]}';

$arr = json_decode($str, true);
$arrne['name'] = "dsds";
array_push( $arr['players'], $arrne );
print_r($arr);

Just check value of print_r($arr); I hope this is what you want. :)

Adding a new array element to a JSON object

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

How to push JSON object in to array using javascript

Observation

  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];data.push(feed);
console.log(data);

How to add element to JSON object using PHP?

Simply, decode it using json_decode()

And append array to resulting array.

Again encode it using json_encode()

Complete code:

<?php
$arr = '[
{
"id":1,
"name":"Charlie"
},
{
"id":2,
"name":"Brown"
},
{
"id":3,
"name":"Subitem",
"children":[
{
"id":4,
"name":"Alfa"
},
{
"id":5,
"name":"Bravo"
}
]
},
{
"id":8,
"name":"James"
}
]';
$arr = json_decode($arr, TRUE);
$arr[] = ['id' => '9999', 'name' => 'Name'];
$json = json_encode($arr);

echo '<pre>';
print_r($json);
echo '</pre>';

How do I add to an existing json file in node.js

If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.

var fs = require('fs')

var currentSearchResult = 'example'

fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
json.push('search result: ' + currentSearchResult)

fs.writeFile("results.json", JSON.stringify(json))
})

How do I add a value to existing array of JSON file in Node JS

When you use fs.appendFile(), the data is added at the end of the file as a string, not as a new array element.

You need to get the content of your JSON file as a JavaScript object, add the property to the array and finally save the new file.

One way to do it is to read the file with fs.readFile(), like suggested by TGW in his comment.

However NodesJS has a convenient method to do that with require():

const fs = require('fs');
const json = require('./address-list.json');

function saveNewAddress(address) {
return new Promise((resolve, reject) => {
json.push({address})
fs.writeFile('address-list.json', JSON.stringify(json), (err) => {
if (err) reject(err)
resolve("File saved.")
})
});
}

saveNewAddress('some_new_adress')
.then(result => {
console.log(result)
})

Insert array of json data into json file using javascript & JSP

Thank you all for replying to this question. The problem is solved. Actually, I send the javascript variable to JSP using Ajax post method. It was more than simple than I thought.`function check(){

 $.ajax({
type: 'POST',
url: "CollectData.jsp",
data: {xydata:arrayData},
dataType: "json",
success: function(resultData) {
alert("here");
console.log("New Data :"+resultData);
//$("#list").html(resultData);
}
});

}`

and finally, Saved into the JSON file

String data =request.getParameter("xydata"); 
JSONObject obj = new JSONObject();
obj.put("arr", data);

try {
FileWriter file = new FileWriter("D:\\test\\testFile.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();}

Exporting array object to file in JSON format

Assuming you are talking about array of objects which you want to download as a josn file then you can go with file-saver.

  1. install file saver npm install file-saver --save
  2. for typescript definitions, install npm install @types/file-saver --save-dev
  3. inside your .ts just import: import { saveAs } from "file-saver";

Note: no need to import the module in app.module.ts, you can directly import the point no. 3 in your ts wherever required


  1. Finally add below code to download json file

    exportTojson() {
    // exportData is your array which you want to dowanload as json and sample.json is your file name, customize the below lines as per your need.
    let exportData = this.users;
    return saveAs(
    new Blob([JSON.stringify(exportData, null, 2)], { type: 'JSON' }), 'sample.json'
    );}
  2. For more details click here.



Related Topics



Leave a reply



Submit