how to use json array key to javascript variable - javascript

i am try json_encode($updateArray);
and this is call by ajax and after ajax success
return me json string on responseText something like this type
{"title":"superAdmin","id":"50"}
now i want to use this two key
like
var text = title;
var id = id;
who can i user this two to as diff. variable.
thanks.

You parse the responseText into an object graph using JSON.parse:
var result = JSON.parse(xhr.responseText);
All modern browsers have JSON.parse now (but not IE7 and earlier; for them, you can use a library like the ones Crockford has on his github page.)
Once you have the object graph (which is just a single object, in your case), you can get the information:
var title = result.title;
var id = result.id;

Use JSON.parse:
var json = '{"title":"superAdmin","id":"50"}';
var obj = JSON.parse(json);
And now, you can do:
var text = obj.title;
var id = obj.id;

Related

Is their is anyway to make json object schema fixed i.e always contains same key

Is their is anyway to make json object schema fixed so that whenever i will create new object it will show same fixed number of key. So that i can change the value for that key whenever required(As like setter and getter).
You're probably mixing json and javascript.
JSON is a data format for communication, it can be used to serailiaze javscript object to the server, but the server can serialize his own objects into JSON, wheter they come from nodeJS, Java, or whatever.
So let's assume you're talking about javascript, this is really easy let's say you want an object People with the field name, *firstname**, dateOfBirth. You can just create a class with his constructor like this :
// creating based fields
function People(){
this.name = null;
this.firstname = null;
this.dateOfBirth = null;
}
// instantiating objects :
var myPeople = new People();
But with that we can still do something like myPeople.foo = "bar". There is no way of preventing that in javascript. However you can make sure yourself that extrafield won't getserialized in JSON with something like this :
// adding method toJson to people
People.prototype.toJson = function(){
return JSON.stringify({name:this.name, firstname:this.firstname, dataOfBirth:this.dateOfBirth});
};
// using it
var myJsonString = myPeople.toJson();
So any extra field you could have need for some manipulation will be ignore on serializing to the serving. I advsied you that because you not only to filter you keys, but to translate some objects before serializing. For instance i never serialize Javascript Date object, i always take the Timestamp (from getTime() method).
I don't know if i understand your question clearly but here is what i came up with:
var schema = function(){
var a=0;
var b=2;
var getA = function(){
return a;
}
var setA = function(newValue){
a = newValue;
}
return {
getA:getA,
setA:setA
}
}
Then when you want a new instance you can do this.
var x = new schema();
x.setA(25);
x.getA();

How to access property of JavaScript object, given string with property's name

I'm getting this data from a service:
{"ok":{"0147852369":"somevalue"}}
I need to read the value, which in this example is "somevalue".
Inside a variable I have the string that represents the name of the property containing "somevalue", like:
var mobilereceiver = "0147852369";
But I can't figure out how to use that string to access the property with the same name.
My latest try is like this:
$http.get(
'url'
)
.success(function(data) {
var response = angular.fromJson(data);
var mobilereceiver = '0147852369';
var messageId = response.ok.mobilereciever;
});
I need to set the last var, messageId which should then hold the "somevalue" of the of the data I'm getting from the service. However, it isn't working. What am I doing wrong?
Let's look at the code you're trying to use:
$http.get(
'url'
)
.success(function(data) {
var response = angular.fromJson(data);
var mobilereceiver = '0147852369';
var messageId = response.ok.mobilereciever;
});
You're very close, in that you recognize that your string mobilereceiver holds the value that needs to be provided as the name of the final property. However, on your last line, when you try to access response.ok.mobilereceiver, that isn't actually referring to the variable mobilereceiver. Instead, it's just looking for a property inside ok that's actually called mobilereceiver. Instead of trying to use the dot notation for accessing properties, what you need to do is use the associative array style accessor:
var messageId = response.ok[mobilereceiver];
This will allow the actual value of mobilereceiver to be passed in as a string, which will be used as the key to look up the value you're trying to access.
You might also want to take a look at angular.fromJson which is a helper function that converts JSON data to an object type structure.

JSON.parse doesn't seem to parse object data?

I am communicating between iframes, but json.parsing to a var then using document.write to dump it doesn't contain anything. But if I alert(e.data), it does.
<script>
window.onmessage = function(e) {
var j = JSON.parse(e.data);
document.write(j);
}
</script>
<script>window.postMessage("[1, 5, 'false']", '*');</script>
For a correctly parse of a string into a JSON object strings keys and values must be wrapped by quotes "
JSON.parse() is defined in ECMA-262, fifth edition, almost any browser supports it.
How to use it?
var json = '{"prop":"first","prop2":1}';
var o = JSON.parse(json);
If you're using jquery, it has a parse json function $.parseJSON, but its slower than native JSON.parse, so it's better to use the jquery function if the JSON object is not available.
var json = '{"prop":"first","prop2":1}';
var o = JSON && JSON.parse(json) || $.parseJSON(json);

Creating json keys on the fly

I would like to create a json object to send as a post array, but I need to create the key on the fly
var id = $('#myInput').val();
var post = {
'product[123]': 'myValue', // this works fine - but isn't dynamic
'product['+id+']': 'myValue' // this does not work
}
Sending it in as a string works fine, but I get an issue when I want to make it more dynamic. Am I missing something really simple here, or am I trying to do something Javascript isn't supposed to do?
(Note that this has nothing to do with JSON. You're not using JSON there, you're using an object initializer. JSON is a textual (not code) format, which is a subset of JavaScript's object initializer syntax.)
Do it outside the object initializer, using [] notation:
var id = $('#myInput').val();
var post = {};
post[product[id]] = 'myValue';
That will take the value (at runtime) of product[id] and use that as the key for the property. If you wanted the key to literally be product[123] when id is 123, you'd use this instead:
post['product[' + id + ']'] = 'myValue';
A more generic discussion:
var a = "foo";
var obj = {};
obj[a] = "bar";
console.log(obj.foo); // "bar"
JavaScript allows you to specify property keys in two ways: Using dotted notation and a literal (obj.foo), or using bracketed notation and a string (obj["foo"]). In the latter case, the string doesn't have to be a string literal, it can be the result of any expression.
Try
post['product[' + id + ']'] = 'myValue';
Why do you use '[ ]' in ids of the object? Avoid to do this.
In your sample, you can do this by the following code:
var id = $('#myInput').val();
var post = {
'123': 'myValue',
id: 'myValue'
}
Or, if you realy realy want to use an arrry (actually, all objects ARE array in JavaScript).
You can write this:
var product=[];
product['123']='something';
product[id]='another';

Accessing Json in Javascript

'[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]'
When I try to access the above like this:
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
It spells out each thing, such as [, {, ", S, and etc.
I also tried doing data[i].SponsorName but obviously got undefined. How should I be accessing this?
You need to parse the JSON string, preferably with JSON.parse. The JSON API is built into more modern browsers and can be provided to older browsers by including Crockford's JSON script. Crockford's script will detect if the browser already provides the API and adds it if not.
With that in place, if your JSON is in a string variable named response, you can:
var parsedResponse = JSON.parse( response );
//run your iterating code on parsedResponse
You would first need to eval() or more ideally JSON.parse() the JSON string in to a Javascript object. This assumes you trust the source of the JSON.
var jsonobj = JSON.parse(data);
// Now view the object's structure
console.dir(jsonobj);
Here's what it looks like after being evaluated and printed out:
var array = JSON.parse('[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]')
array[0].AccountingManager; // "me"
Or everyone's favorite library, since IE7 and below don't have native support:
$.parseJSON('[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]')
You parsed the Json string first, right?
var data = '[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]';
data = JSON.parse(data);
alert(data.SponsorName);
JSON.parse, when available, is the preferred method over "eval" because of security and performance issues.
You've got a JSON array followed by an object:
var data = [{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}];
alert(data[0].SponsorID);

Categories