I've a json string that I've turned into an object with parseJSON (where #get_my_json_data is a textarea to enter json)
var data = jQuery.parseJSON( $("#get_my_json_data").val() );
cool, I've now got an object to see the whole structure.
What I need to do is to alter the KEY of one node. BUT.. I don't know what it is (so can't just do a stringify and search/replace). I DO know the exact position that it'll be...
Here's a sample structure or the json in the textarea.
{
"MasterData": {
"|-|-|ID|-|-|": {
"menu": {
"Tabs": [
{
"Name": "Home",
"TabText": "Home"
},
.........
I need to find the KEY of the second item, in this example, it's: '|-|-|ID|-|-|'
When they edit again, it'll be different. SO how on earth can I update the node key AFTER MasterData and write the whole thing?
I've tried an $.each loop but it just keeps killing the whole 'array'
---- UPDATE ---
I ended up doing this and it worked great!
var data = jQuery.parseJSON( $("#get_my_json_data").val() );
var keys = Object.keys( data.MasterData );
data.MasterData[$(this).val()] = data.ConteMasterDatatData[keys[0]];
delete data.MasterData[keys[0]];
$("#get_my_json_data").val(JSON.stringify(data));
Soo if i understood what you want, you want to replace the property name in the parsed object.
Try this:
//Get the keys
var innerkeys = Object.keys(myObject.MasterData);
//Create a property with the information from the first key
myObject["myNewKey"] = myObject.MasterData[innerkeys[0]];
//Delete old property
delete myObject.MasterData[innerkeys[0]];
If you parse the object to json it should be as you expected (not tested)
Information obtained from:
how-to-list-the-properties-of-a-javascript-object
how-do-i-remove-a-property-from-a-javascript-object
Related
My Existing Code and Explanation
Working Fine, But I want to Create a template like Its should read JSON Data that Having keys in any name, I am Always reading data from JSON object in 2nd Position
Now I read the JSON that passed in the argument (data) inside that using the for loop extract single object in group, after that get the data using key(Module_Name).. I know the key(Module_Name) is always present in second position only, Now its Working Fine with keyname rather i want to fetch the data using position, that also used as template in my other modules
/* render Screen Objects */
screenRenderer.displayScreens = function(data)
{
screenRenderer.renderLayout(function(cont, boo)
{
if (boo)
{
for(i=0;i<data.length;i++)
{
var buttons = "<button class='screen_button'>"+data[i].Module_Name+"</button>";
$("#screen-cont").append(buttons);
}
}
else
{
scr_cont.show();
}
})
}
This is My Requirement, kindly awaiting suggestions, answers..
Thanks in Advance
You can use the function Object.keys(obj) to get all keys of an object as array, which you can access with an Index and than use the String you get to access the property.
So it could look like this:
var obj = data[i];
var keys = Object.keys(obj);
var result = obj[keys[1]];
Hope this is what you want.
I´m having a problem with a javascript function.
The idea is read the content of a file with javascript. Everything is working ok, I can see the content of the file, just now I want to organize the content.
And what I meant with organize is:
My file have a lot of strings, for example: tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept.....
And everything is a line of strings, and at the end is that all what I see...
My goal is, when I read the file, at the end it have to show something like this:
Tel: 01234567
01456789
Dept: Level1
Level2
There is a way to have something like that?
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
So basically your file has attributes and data for the respective attribute surrounded by the attribute name + #?
The easiest thing would be to have the file in a common format for data, e.q. JSON. Then you could just use the attributes from the object you get by JSON.parse();
However, if you cannot change the file structure you will have to programm something that splits your string into the desired parts and creates an object out of the attributes to work with.
For the string you presented you could do one string.split(" ") to get every attribute singled out, resulting in an array like this:
Array [ "tel#01234567#tel", "tel#01456789#tel", "dept#level1#dept", "dept#level4#dept" ]
Afterwards you can iterate over the array and string.split("#") again for each element which gives you this:
array[0].split("#");
Array [ "tel", "01234567", "tel" ]
Then you can use the first index of the array as attribute name and the second one as its data. You could put that into an object and afterwards refer from the attribute straight to the data:
var string = "tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept";
var array = string.split(" ");
var dataObject = {};
for(var i in array){
var element = array[i].split("#");
if(dataObject.hasOwnProperty(element[0])){
dataObject[element[0]].push(element[1]);
}else{
dataObject[element[0]] = [element[1]];
}
}
In the end you have an object that has all the attributes as its properties and the corresponding data stored in an array for each property. With that you should be able to work right? :)
When you read the file in you could use JS split to separate the content based on the delimiters.
Check it out here: http://www.w3schools.com/jsref/jsref_split.asp
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
Not very familiar with JSON data and how to create it using JavaScript.this is what i am trying
i have created two JS variables
var json={};
var json1={};
i have some certain loops to iterate data and loops like
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=JSON.stringify(json);
}
Doing this i am getting following output
Required: "{"Center":"radio_Required_Center_0,radio_Required_Center_1,","Left":"radio_Required_Left_0,"}"
which is not a valid JSON format.My idea id to create a outer-key say Required and than an inner one's in my case Center and Left
so that i can iterate each value with respect to key Center (i can break the string based on ')
i am not sure how to create correct structure and i don't want to do it on server side which can be done easily.
any solution or hint will really be helpful.
Edit
var data= JSON.stringify(json1);
giving following output
{"Required":"{\"Center\":\"radio_Required_Center_0,radio_Required_Center_1,\",\"Left\":\"radio_Required_Left_0,\"}"}
which is valid JSON data, now i need to execute some code based on the data in the JSON and here are my requirements
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
My real challenge is at step number 2 and 3 where i need to fetch the keys and its associated values and those key and not predefined so i can not access them based on there name.
I am thinking of a way to get key and its values without hard coding key names and execute my logic.
is it possible in by this approach or not?
If you're using a modern version of Javascript, it comes with JSON functions built-in.
var jsonString = JSON.stringify(jsobject);
...to convert a JS object into a JSON string.
(See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)
and
var jsOject = JSON.parse(jsomString);
...to convert back in the other direction.
(see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)
The only time you need to worry about this not being built-in is if you're using an old browser - for example, older versions of IE. However, in this case, there are polyfill libraries like this one that you can load which will implement the above syntax for you.
If you're just trying to compose one big JSON object, you don't need to stringify one JSON object before adding it to another... So instead of doing JSON.stringify(json) you can just do json1[outerKey]=json
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=json;
}
try jsonlint.com to validate your JSON
This is valid:
{
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
This is valid too:
{
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
This isn't:
Required: {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
using JSON.stringify() is the right way of converting javascript objects to JSON string format. However if you want to put it in a variable you should do that first, later in the last step you convert to JSON string.
var output = { "Required": yourpreviousjsonvar },
jsonString = JSON.strinify(output);
EDIT:
You need to process the data first you probably won't even need the JSON string if I understand you right. (=> if however you already got a string you need it parsed first. Do it using JSON.parse(yourjsonstring))
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
having this as variable:
var a = {
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
// step 1
console.log(a.Required);
// step 2
console.log(a.Required.Center);
console.log(a.Required.Left);
// step 3
var center = a.Required.Center.split(',');
var left = a.Required.Left.split(',');
// step 4
for(var i = 0; i<center.length; i++){
console.log("doing somthing with", center[i]);
}
Here is a fiddle => use Chrome/safari/Opera's developpertools and check the console to check the output. Or use firebug (in firefox) Or IE9 or greater (F12).
Use native Javascript toSource :
var obj= new Object();
var obj1= new Object();
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
obj.innerKey=jsonValues;
}
obj1.outerKey=obj;
}
json = obj.toSource();
json1 = obj1.toSource();
I'm new to jQuery and just playing for fun. I have some code that I want to try to modify for my needs but the current js file is getting its data from google spreadsheets and then returning each item as objects. I don't use json to pass data from my server to jQuery so I'm wondering how I can convert json to objects.
The current way its doing it is(tabletop is the name of their js program that gets data from google docs):
Tabletop.init({
key: timelineConfig.key,
callback: setupTimeline,
wanted: [timelineConfig.sheetName],
postProcess: function(el){
//alert(el['photourl']);
el['timestamp'] = Date.parse(el['date']);
el['display_date'] = el['displaydate'];
el['read_more_url'] = el['readmoreurl'];
el['photo_url'] = el['photourl'];
}
});
I have added alerts all over the file and I think this is the area that gets the data and passes it on. I was thinking of trying to replace items in their object with objects from my json and see if it changes anything, but I'm unsure. Typrically I pass individual items via json,hashmaps, and lists, not sure how it works with objects or how to access objects(I simply call url's that I create for the requests, $("#user-history").load("/cooltimeline/{{ user.id }}");). But where do I start if I want to turn json data into objects?
If it helps, here's the demo of what I'm trying to do(but by having it use json data).
p.s. I'm really looking for the logic of how to complete what I'm trying to do and perhaps some ideas I'm missing so I can google them and learn.
Use use function JSON.parse(json) :) Or jQuery.parseJSON(json)
var json = '{"a":2}';
var object = JSON.parse(json);
alert(object.a);
You should see alert with message: 2
I don't realy know if I understand your comment, but maybe you want just do this:
postProcess: function(el){ //here el is JSON string
el = JSON.parse(el); // now el is an object
el.timestamp = Date.parse(el.date);
el.display_date = el.displaydate;
el.read_more_url = el.readmoreurl;
el.photo_url = el.photourl;
return el;
}
Btw. you do not need to use brackets on know property names without not standard names:
el['timestamp'] === el.timestamp
It will be easier if you paste your JSON