append json objects into json array - javascript

I have a form and would like to append the contents of it to an existing array.
I am using JSON.stringify( $('#myForm').serializeObject() ) to convert my form elements into json objects.
The form has user info that i would like to append into myArr then append this list into an existing array.
myArr is populating fine, its just appending that into existingJsonArray i seem to be having problems with.
I saw this but since JSON.stringify creates the full json array would i need to knock out the [{ and }] ?
Is this the correct approach?
var existingJsonArray = [];
var myArr = [];
myArr.unshift( JSON.stringify( $('#myForm').serializeObject() ) );
existingJsonArray.unshift(myArr);

Please notice that JSON is the string representation of objects - and not suited well for manipulating them.
var array = [], // an Array literal in JavaScript code
formObject;
formObject = $('#myForm').serializeObject(); // an object representing the form
array.unshift([formObject]); // not sure why you need the nested array
// create string containing JSON representation of the array:
var jsonString = JSON.stringify(array);

Related

Populate Javascript Array with JSON Data

I am attempting to load a large set of JSON files into an array to be referenced later but Node keeps stating they're undefined. I have code along the lines of:
var myarray = [];
(...)
var loading_num = 001; // will be incremented in a loop to load data
myarray[loading_num] = fs.readFileSync("data/" + loading_num);
(...)
var reference_num = "001"; // the number being used to pull the appropriate record
(...)
console.log(myarray[reference_num].name); // just testing to attempt to decipher why it doesn't work, I'll actually be using the data obviously
Each JSON file does have a value named name and I have not implemented logic to load all of them yet as I am still just trying to get one to work.
Am I misunderstading something about Javascript arrays or objects? What am I doing wrong? There's a lot of files and they can vary in number so I have to load them in some similar fashion.
You should parse the file contents so the raw data is converted into JavaScript objects.
myarray[001] = JSON.parse(fs.readFileSync("data/001"));
First of all. fs.readFileSync reads arbitrary files. If you know your file is JSON and you want to convert it to js you need to parse it using JSON.parse.
Then 001 is 1 if you want it to be a string wrap it with quotes '001'
Array indices starts from 0.
var myarray = [];
myarray.push(JSON.parse(fs.readFileSync("data/001")));
console.log(myarray[0].name);
Or
var myarray = {}; // use object
myarray['001'] = JSON.parse(fs.readFileSync("data/001"));
var reference_num = "001";
console.log(myarray[reference_num].name);

How to convert json array to javascript array using specific values

i want to convert a json array (string) to javascript array using just some specific values. The json array is :
[{"id":47,"libelle":"famille de test"},{"id":1,"libelle":"GEOLOCALISATION"},{"id":4,"libelle":"OUTILS"},{"id":2,"libelle":"PROPRETE"},{"id":3,"libelle":"URGENCE"}]
and i want to get something like this ["famille de test", "GEOLOCALISATION", ...] using just libelle values.
I tried to use $.map but didn't work out.
The map implementation should work:
var jsonStr = '[{"id":47,"libelle":"famille de test"},{"id":1,"libelle":"GEOLOCALISATION"},{"id":4,"libelle":"OUTILS"},{"id":2,"libelle":"PROPRETE"},{"id":3,"libelle":"URGENCE"}]';
var arr = JSON.parse(jsonStr);
var libelle = arr.map(function(x) { return x.libelle; });
First, you must turn your JSON string into a JavaScript Array by using JSON.parse(yourJSONString). After that, it is a simple JavaScript array and you can use the map method you tried

Store a JavaScript array in the DB and get array back when needed

I have a multidimensional associative JavaScript array with some metabox data and I need to store that array in the WordPress database (in a single column).
And I also want to get that stored array back in the metabox call back function and use the values in the array to populate the relevant fields.
This is what I've done so far...
var data = [
{ key: 'cardK', val: 13 },
{ key: 'cardQ', val: 12 },
{ key: 'cardAJ', val: 11 },
];
var serializedData= JSON.stringify( data );
This outputs a string look like this
[[1,2],[3,4],[5,6]]
Now I can store this in the DB in a single column. But how can I get this back as an array and use it to populate the fields ?
Save the string as JSON, like this:
var data = [[1,2],[3,4],[5,6]];
var serializedData = JSON.stringify(data);
Before you convert make sure you replace any data which has changed in the json to make it valid json before using json_decode().
use this function:
str_replace();
To convert it into array on PHP side:
json_decode(data, true); // returns array
json_decode(data); // returns an object, not an array.
When you get the JSON string back from MySQL, you can turn it back into an array with JSON.parse(), like this:
var returnedArr = JSON.parse(returnedData);

Show Json Object In TextBox

I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference

Convert Javascript string or array into JSON object

I have a JavaScript variable with comma separated string values - i.e. value1,value2,value3, ......,valueX,
I need to convert this variable's values into a JSON object. I will then use this object to match user enteredText value by using filterObj.hasOwnProperty(search)
Please help me to sort this out.
What you seem to want is to build, from your string, a JavaScript object that would act as a map so that you can efficiently test what values are inside.
You can do it like this :
var str = 'value1,value2,value3,valueX';
var map = {};
var tokens = str.split(',');
for (var i=tokens.length; i--;) map[tokens[i]]=true;
Then you can test if a value is present like this :
if (map[someWord]) {
// yes it's present
}
Why JSON? You can convert it into an array with split(",").
var csv = 'value1,value2,value3';
var array = csv.split(",");
console.log(array); // ["value1", "value2", "value3"]
Accessing it with array[i] should do the job.
for (var i = 0; i < array.length; i++) {
// do anything you want with array[i]
}
JSON is used for data interchanging. Unless you would like to communicate with other languages or pass some data along, there is no need for JSON when you are processing with JavaScript on a single page.
JavaScript has JSON.stringify() method to convert an object into JSON string and similarly JSON.parse() to convert it back. Read more about it
All about JSON : Why & How
Cheers!!
JSON format requires (single or multi-dimensional) list of key, value pairs. You cannot just convert a comma separated list in to JSON format. You need keys to assign.
Example,
[
{"key":"value1"},
{"key":"value2"},
{"key":"value3"},
...
{"key":"valueX"}
]
I think for your requirement, you can use Array.

Categories