JSON array-like object, add item - javascript

I have a JSON file which contains:
[{"id":1,"first_name":"Judith","email":"jshaw0#wikipedia.org"},
{"id":2,"first_name":"Sarah","email":"sross1#infoseek.co.jp"},
{"id":3,"first_name":"Dorothy","email":"dgreene2#posterous.com"},
{"id":4,"first_name":"Christine","email":"cnichols3#techcrunch.com"},
{"id":5,"first_name":"Theresa","email":"trogers4#xrea.com"},
{"id":6,"first_name":"Rebecca","email":"rpeterson5#mlb.com"},
{"id":7,"first_name":"Chris","email":"cbailey6#yellowpages.com"},
{"id":8,"first_name":"Howard","email":"hbailey7#miibeian.gov.cn"},
{"id":9,"first_name":"Sara","email":"ssimpson8#techcrunch.com"},
{"id":10,"first_name":"Lois","email":"lmartinez9#dion.ne.jp"},
{"id":11,"first_name":"Jeffrey","email":"jhalla#intel.com"},
{"id":12,"first_name":"Teresa","email":"tcampbellb#usnews.com"},
{"id":13,"first_name":"Susan","email":"skingc#wired.com"},
{"id":14,"first_name":"Richard","email":"rpattersond#omniture.com"},
{"id":15,"first_name":"Ronald","email":"rgreenee#wordpress.org"}]
I want to add one more element to it but I can't figure it out how.
I have the following node code:
var jsonfile = require('jsonfile');
var util = require('util');
var file = 'data.json';
var jsonObj = {};
jsonfile.readFile(file, function(err, obj) {
jsonObj = obj;
new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
//jsonObj.push(new_obj)
console.log(typeof jsonObj);
/*jsonfile.writeFile(file, jsonObj, function (err) {
console.error(err)
})*/
});
I've tried to use push method, but obviously is not working because it is an object not an array, even if it looks as an array. Which would be a good way to add another row at the end of the object (or array - I'm confused)?

I believe you're forgetting to parse JSON. After reading the file, your code should be:
jsonObj = JSON.parse(obj);
instead of straight assignment.

Declare the variable
var new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
And then use push() as you have done already. Give it a try. It will work only if obj is json object as you mentioned in question.

Related

papa.unparse creates empty csv files

function savecsv(){
var obj = {};
$("input").each(function(){ obj[this.id]=this.value;});
console.log(obj);
var csv = Papa.unparse(obj);
return csv;
}
Hey i have some, prolly simple problems using papa.unparse, it creates empty csv files. I tried some of the config possibilities but couldnt make it work. Someone could give me a hand? I only want the user beeing able to save his input(id and value) for later use.
Thx!
Try this:
function savecsv(){
var obj = [];
$("input").each(function(){ obj.push([this.id, this.value]); });
console.log(obj);
var csv = Papa.unparse(obj);
return csv;
}

Load a JSON file into a JS object

I try to load a json file into a JavaScript var but it just doesn't work out.
var jsonString = JSON.stringify('./test.json');
var obj = JSON.parse(jsonString);
console.log(obj.details.ProductID);
it says that it can't read property ProductID of undefined.
What am I doing wrong here ?
You need to make an AJAX call to get the file. $.getJSON was intended for exactly this purpose:
$.getJSON('./test.json', function(obj) {
console.log(obj.details.ProductID);
});
If you are using jQuery:
$.getJSON( "/test.json", function( obj ) {
console.log(obj.details.ProductID);
});
JSON.stringify() first argument needs to be a valid JSON string, not a file.
You need to use AJAX to retrieve file from server:
$.getJSON('./test.json', function(responseObject){
var obj = responseObject
console.log(obj)
})
In case it helps anyone, just use this:
const dataObjectFromFile = require('./path/to/datafile.json');

getting json data from tree and feeding through to associative array

I'm trying to read a JSON API and parse the data into an associative array but I can't seem to get it to work. I must be doing something wrong.
Here is my code:
var matchedValues = {};
$.getJSON(url ,function(data) {
$.each(data, function() {
var value = this["value"];
var climb = this["climb"];
matchedValues[value] = climb;
});
});
console.log(matchedValues); //Outputs Object{}
Any ideas? I don't think I am console logging it correctly or maybe I'm doing something wrong?
Thanks
matchedValues is an Object not an array. try something likmatchedValues['your_key'] to get the value.
I assume that the data coming back from the ajax call is a JSON string, which you wish to parse. If that’s the case, then the problem is already solved using JavaScript’s JSON object:
var matchedValues = {};
$.getJSON(url ,function(data) {
matchedValues=JSON.parse(data);
});
console.log(JSON.stringfy(matchedValues)); //Outputs Object{}
As you see in the above example, you have to reverse the process in order to print it out.
See JSON MDN Article
Try this approach from jquery documentation
EDIT:
$.getJSON(url, function(data) {
var matchedValues = {};
$.each(data, function(key, val) {
items[key] = val;
});
If I understood your question, then your data is an Array of objects, and you want to consolidate them in a big object.
If got it right, then use this approach:
var matchedValues = {};
$.getJSON("ajax/test.json", function(data) {
for (var i = 0; i < data.length; i++) {
for (key in data[i]) {
matchedValues[key] = data[i][key];
}
}
console.log(matchedValues); //this should print your object.
});
The data objects must have different keys or they will be overlapsed.

How to serialize File object to JSON? [duplicate]

I want to convert an HTML input file to a JSON string like this:
var jsonString = JSON.stringify(file);
console.log( file );
console.log( jsonString );
Now, in my Firebug it logs as:
File { size=360195, type="image/jpeg", name="xyz.jpg", mehr...}
Object {}
Why is the jsonString empty?
Background info: I want to send the file-reference with JSONP to another PHP server.
Additional Information: I want to convert only the file-pointer (reference) to a string, to send it via GET.
It is not possible to directly convert a File object into JSON using JSON.stringify in Chrome, Firefox and Safari.
You can make a work around to convert File object to string using JSON.stringify
Ex:
// get File Object
var fileObject = getFile();
// reCreate new Object and set File Data into it
var newObject = {
'lastModified' : fileObject.lastModified,
'lastModifiedDate' : fileObject.lastModifiedDate,
'name' : fileObject.name,
'size' : fileObject.size,
'type' : fileObject.type
};
// then use JSON.stringify on new object
JSON.stringify(newObject);
You can also add the toJSON() behavior to your File object
EX:
// get File Object
var fileObject = getFile();
// implement toJSON() behavior
fileObject.toJSON = function() { return {
'lastModified' : myFile.lastModified,
'lastModifiedDate' : myFile.lastModifiedDate,
'name' : myFile.name,
'size' : myFile.size,
'type' : myFile.type
};}
// then use JSON.stringify on File object
JSON.stringify(fileObject);
Note: send a File Object to server using the POST HTTP method.
You have to read the file content using the FileReader API. The File object does not contain the file content (it is just a pointer toward the file, which allows you to read it later).
You can check out this HTML5Rocks article to find out more about the usage of this API.
var file = getAFile( );
var success = function ( content ) {
console.log( JSON.stringify( content ) ); }
var fileReader = new FileReader( );
fileReader.onload = function ( evt ) { success( evt.target.result ) };
fileReader.readAsText( file );
In case anyone is still looking for a solution to this please see my answer on a different post and working example on JSFiddle.
JS:
function getFiles(){
var files = document.getElementById("myFiles").files;
var myArray = [];
var file = {};
console.log(files); // see the FileList
// manually create a new file obj for each File in the FileList
for(var i = 0; i < files.length; i++){
file = {
'lastMod' : files[i].lastModified,
'lastModDate': files[i].lastModifiedDate,
'name' : files[i].name,
'size' : files[i].size,
'type' : files[i].type,
}
//add the file obj to your array
myArray.push(file)
}
//stringify array
console.log(JSON.stringify(myArray));
}
HTML:
<input id="myFiles" type="file" multiple onchange="getFiles()" />
You just need a custom replacer:
function stringify(obj) {
const replacer = [];
for (const key in obj) {
replacer.push(key);
}
return JSON.stringify(obj, replacer);
}
const json = stringify(file);
console.log(file);
console.log(json);
Now you should see:
File {name: "xyz.jpg", type: "image/jpeg", size...}
'{"name":"xyz.jpg","type":"image/jpeg","size"...}'
Instead of looping through, or rather extracting each key one after the other, i came up with this function and i've used it image input.
const fileObject = e.target.files[0];
important notice
//dont use shorthand for of loop
for (const [key, value] in Object.entries(x))
it can't loop through a file object in JS
Use this code instead
const imageObject = {};
for (const key in fileObject) {
const value = fileObject[key];
const notFunction = typeof value !== "function";
notFunction && (imageObject[key] = value);
}
console.log(imageObject) // => should give you a normal JS object now
When you pass a json string Javascript internally trnsform it to Json object and hence no need to parse it.
follow steps in case of of json file ->
$('#inp_import_template')[0].files[0]
Now your json file is transformed to json object (Javascript).
var obj = {
name: 'dashu3f'
};
var stringObj = JSON.stringify(obj);
console.log(typeof stringObj);
console.log(stringObj);
open terminal this Folder file and run node json.js

How can I serialize an input File object to JSON?

I want to convert an HTML input file to a JSON string like this:
var jsonString = JSON.stringify(file);
console.log( file );
console.log( jsonString );
Now, in my Firebug it logs as:
File { size=360195, type="image/jpeg", name="xyz.jpg", mehr...}
Object {}
Why is the jsonString empty?
Background info: I want to send the file-reference with JSONP to another PHP server.
Additional Information: I want to convert only the file-pointer (reference) to a string, to send it via GET.
It is not possible to directly convert a File object into JSON using JSON.stringify in Chrome, Firefox and Safari.
You can make a work around to convert File object to string using JSON.stringify
Ex:
// get File Object
var fileObject = getFile();
// reCreate new Object and set File Data into it
var newObject = {
'lastModified' : fileObject.lastModified,
'lastModifiedDate' : fileObject.lastModifiedDate,
'name' : fileObject.name,
'size' : fileObject.size,
'type' : fileObject.type
};
// then use JSON.stringify on new object
JSON.stringify(newObject);
You can also add the toJSON() behavior to your File object
EX:
// get File Object
var fileObject = getFile();
// implement toJSON() behavior
fileObject.toJSON = function() { return {
'lastModified' : myFile.lastModified,
'lastModifiedDate' : myFile.lastModifiedDate,
'name' : myFile.name,
'size' : myFile.size,
'type' : myFile.type
};}
// then use JSON.stringify on File object
JSON.stringify(fileObject);
Note: send a File Object to server using the POST HTTP method.
You have to read the file content using the FileReader API. The File object does not contain the file content (it is just a pointer toward the file, which allows you to read it later).
You can check out this HTML5Rocks article to find out more about the usage of this API.
var file = getAFile( );
var success = function ( content ) {
console.log( JSON.stringify( content ) ); }
var fileReader = new FileReader( );
fileReader.onload = function ( evt ) { success( evt.target.result ) };
fileReader.readAsText( file );
In case anyone is still looking for a solution to this please see my answer on a different post and working example on JSFiddle.
JS:
function getFiles(){
var files = document.getElementById("myFiles").files;
var myArray = [];
var file = {};
console.log(files); // see the FileList
// manually create a new file obj for each File in the FileList
for(var i = 0; i < files.length; i++){
file = {
'lastMod' : files[i].lastModified,
'lastModDate': files[i].lastModifiedDate,
'name' : files[i].name,
'size' : files[i].size,
'type' : files[i].type,
}
//add the file obj to your array
myArray.push(file)
}
//stringify array
console.log(JSON.stringify(myArray));
}
HTML:
<input id="myFiles" type="file" multiple onchange="getFiles()" />
You just need a custom replacer:
function stringify(obj) {
const replacer = [];
for (const key in obj) {
replacer.push(key);
}
return JSON.stringify(obj, replacer);
}
const json = stringify(file);
console.log(file);
console.log(json);
Now you should see:
File {name: "xyz.jpg", type: "image/jpeg", size...}
'{"name":"xyz.jpg","type":"image/jpeg","size"...}'
Instead of looping through, or rather extracting each key one after the other, i came up with this function and i've used it image input.
const fileObject = e.target.files[0];
important notice
//dont use shorthand for of loop
for (const [key, value] in Object.entries(x))
it can't loop through a file object in JS
Use this code instead
const imageObject = {};
for (const key in fileObject) {
const value = fileObject[key];
const notFunction = typeof value !== "function";
notFunction && (imageObject[key] = value);
}
console.log(imageObject) // => should give you a normal JS object now
When you pass a json string Javascript internally trnsform it to Json object and hence no need to parse it.
follow steps in case of of json file ->
$('#inp_import_template')[0].files[0]
Now your json file is transformed to json object (Javascript).
var obj = {
name: 'dashu3f'
};
var stringObj = JSON.stringify(obj);
console.log(typeof stringObj);
console.log(stringObj);
open terminal this Folder file and run node json.js

Categories

Resources