Get a certain value from a json object - javascript

I have a json object
eg
{
"href":"Test",
"commentID":"12334556778"
}
Is there a way just to get the second line i.e. "commentID":"12334556778"
I'm using
JSON.stringify(json)
Thanks all

You can create another object containing only the commentID property:
var obj = {
"href": "Test",
"commentID": "12334556778"
};
var result = JSON.stringify({
"commentID": obj.commentID
});

JSON.stringify accepts a third argument which handles white-space in the output. If the third argument is present and "truthy", line-breaks will be inserted and each level will be indented using the argument's string value, or a number of spaces if a number is passed. Using this technique, you can get the browser to insert line-breaks and then split on those line-breaks in the result:
var obj = {
"href":"Test",
"commentID":"12334556778"
},
arr = JSON.stringify(obj, null, 1).split("\n");
alert(arr[2]);
//-> ' "commentID": "12334556778"'
Working demo: http://jsfiddle.net/AndyE/ercRS/ (requires browsers with JSON/trim)
You might want to trim any leading white space or trailing comma, but I'll leave that up to you.

if you have a JSON object at hand, just use it like you would use an array.
var jsonObject = {
"href":"Test",
"commentID":"12334556778"
}
alert(jsonObject['commentID']); // alerts 123445678
JSON.stringify() is used if you want to send the data back to your server.

Related

how to get required output from json stringify array

My array look like this after use this code -:
var array=xmlhttrequest.responseText;
console.log(array);
["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]
I want value of isvalid , how can i get this .
That's a strange response. It's a stringified array, and that array contains a single item, which is another stringified object. Here's one option:
const responseText = String.raw`["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]`;
const [ stringItem ] = JSON.parse(responseText);
const itemObj = JSON.parse(stringItem);
const isvalid = itemObj.result.isvalid;
console.log(isvalid);
Note: While testing like this, you have to use String.raw so that the single backslashes are interpreted as literal backslashes and not unnecessary escape characters
The whole thing is an array as you can see it is wrapped inside [ ]. The inner content is a string, so you need to JSON.parse to convert into an object. Here is how you will get it JSON.parse(myData[0]).result.isvalid
var myData = ["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"];
console.log("Is Valid: "+JSON.parse(myData[0]).result.isvalid);
use JSON.parse:
var obj = JSON.parse(array);
but I would try and eliminate all the unnecessary chars before using string.replace:
var json = array.replace("\", "");

Is it possible to multiply values in JSON?

Is it valid in JSON to set value of key as the result of multiplaying/adding two variables/values/string+number/string+string/etc.?Is it possible?
F.e
{
"string": "600*"+40
}
JSON isn't code. It's not JavaScript. It's just a format for writing data. It can't do anything dynamically.
If you wanted to do something like that, you'd have to do it with whatever is creating the JSON.
With JavaScript, you can do something like this:
const jsonStr = '{ "value": 600 }'; // load your JSON from somewhere
const data = JSON.parse(jsonStr); // parse JSON
data.value *= 40; // do stuff
console.log(JSON.stringify(data)); // turn back into JSON.
Note, if it was something like { "value": "600" } where the value is a string, not a number (note the quotation marks ("")), you'd have to remember to parseInt first: data.value = parseInt(data.value) * 40
In short, no. You can't multiply Strings and JSON means that it's a string representation of a Javascript Object.
I think you can save it this way
{
"string": "600+40"
}
or
{
"string": "600*40"
}
but it will only be string. If you want to do math on it you have to convert it.

Access value from JavaScript object via array-string

my problem is that i have a json-object with and array into here an example.
var object = {
'items':['entry1','entry2']
}
I want to access 'entry2' over a constant string that I receive and shouldn't be changed.
var string = 'items[1]';
The only way I'm solving this problem is over the eval function...
eval('object.'+string);
This returns me entry2.
Is there any other way to achieve this without using eval()?
Like object[string] or object.string
Supposing your string is always the same form, you could extract its parts using a regex :
var m = string.match(/(\w+)\[(\d+)\]/);
var item = object[m[1]][+m[2]];
Explanation :
The regex builds two groups :
(\w+) : a string
\[(\d+)\] : some digits between brackets
and those groups are at index 1 and 2 of the array returned by match.
+something parses the number. It's not strictly needed here as the array accepts a string if it can be converted but I find the code more readable when this conversion is explicited.
On top of dystroy's anwser, you can use this function:
function getValueFromObject(object, key) {
var m = key.match(/(\w+)\[(\d+)\]/);
return object[m[1]][+m[2]];
}
Example:
var object = {
'items':['entry1','entry2']
}
var string = 'items[1]';
var value = getValueFromObject(object, string); //=> "entry2"
First, you can get the array from inside:
var entries = object.items // entries now is ['entry1','entry2']
Then you need to index that to get the second item (in position 1). So you achieve what you want with:
var answer = entries[1] // answer is now 'entry2'
Of course, you can combine this to get both done in one step:
var answer = object.items[1] // answer is now 'entry2'
... I can see this is a contrived example, but please don't call your Objects 'object', or your Strings 'string' :s
try something like this
object.items[1];

Find the length of an JSON object

I have a JSON like the following.
How can I find the length of air in console,
console.log (block.number.path[i].air.length);
{ "block": [
{ "number": "36",
"path": [
{ "air": "[{\"name\":\"0\"},{\"name\":\"1\"},{\"name\":\"2\"}]" },
{ "water": "[{\"name\":\"3\"},{\"name\":\"4\"},{\"name\":\"5\"}]" },
{ "sand": "[{\"name\":\"6\"},{\"username\":\"7\"},{\"name\":\"8\"}]" }
]
}
]
}
air itself contains a JSON encoded array, which you have to decode first:
// your obj in here
var obj = { "..." : "..." };
// grab the respective length of the "air" attribute
var air = JSON.parse( obj.block[0].path[0].air );
console.log( air.length );
http://jsfiddle.net/pLAny/
You can solve this like so:
var length = JSON.parse(block.number.path[i].air).length;
console.log(length);
It kind of looks like some of that JSON got malformed. "air", "water", and "sand" are all JSON arrays...but parsed out into strings. If you're the one generating the JSON, look into that, because it doesn't seem right. As the other answers point out, it's still solvable in Javascript using JSON.parse(), as long as you can be sure your target browsers have that interface (most modern ones).
For any JSON array (anything declared using [] brackets) you can check its .length property.
Given that json is a variable containing your JSON, you can do:
json["block"][0]["path"][0]["air"].length
Block is an array, so you have to access to the element first:
a.block[0].path[0].air.length
where a is the variable where you are holding the data.

Passing a external variable in JSON.parse function

I am trying to get a value from json by using the JSON.parse function. My json response is given below:
{
"rows": 10,
"os": "0",
"page": "1",
"total": "122",
"projects": {
"P143841": {
"id": "P143841",
"locations": [{
"geoLocId": "0002220957",
"latitude": "3.866667",
"longitude": "11.516667"
}],
}
}
}
I am able to get the value 10 if I do JSON.parse(obj.rows) but if I assign the rows to a variable say var value = rows and then I pass it to the JSON.parse(obj.value) function I got undefined.
P.S. I won't be knowing the names of the response parameters, i.e. i won't know if it will be rows or os quoting from the above example. I will be retrieving them from a database. If I perform the code below:
for (var i=0;i<length;i++) {
var value = responseParam_array[i];
console.log(obj.value);
}
I get the output but any help will be much appreciated.
As per the other answers you shouldn't need to parse individual properties, just parse the original JSON and then operate on the resulting object.
But as for this problem:
"if I assign the rows to a variable say var value = rows and then I pass it to the JSON.parse(obj.value) function I got undefined"
If value is a variable holding the name of a property of obj then you need:
obj[value]
// NOT
obj.value
When you use "dot" notation the part on the right of the dot is taken as the literal name of the property, not as a variable. Using the square-bracket syntax the expression in the brackets is evaluated and its result is taken as the property name.
you should be json-parsing your whole object and using the parsed object afterwards (you dont need to parse every property for itself)
var strObj = '{"rows": 10,"os": "0","page": "1","total": "122","projects":{"P143841":{"id":"P143841",}}';
var obj = JSON.parse(strObj);
var rows = obj.rows;
If I understand your question:
var str = '{ "some": "JSON String like the one above with", "rows": 10 }';
var parsed = JSON.parse(str);
var whatYouWant = parsed.rows;

Categories