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;
Related
I am converting XML message with attributes to JSON and assigning to a variable. Now variable x has the converted JSON message. Now I want to extract the key value pairs from that variable x(string).
Please check the below details. XML Message is
<?xml version="1.0" encoding="UTF-8"?>
<OBJECT key="postorder" type="TEMP">
<TEMP>
<ROW order-version-id="1"
layout-type="2"
order-no="3"
order-action="4"
estimated-price="5"
orig-price="6"
quantity="7"
orig-quantity="8"
quantity-type="6"
trade-currency="7"
base-currency="8"
settlement-currency="9"/>
</TEMP>
</OBJECT>
and I am converting it using fast-xml-parser and the output is as below
{
"OBJECT":{
"key":"postorder",
"type":"TEMP",
"TEMP":{
"ROW":{
"order-version-id":"1",
"layout-type":"2",
"order-no":"3",
"order-action":"4",
"estimated-price":"5",
"orig-price":"6",
"quantity":"7",
"orig-quantity":"8",
"quantity-type":"6",
"trade-currency":"7",
"base-currency":"8",
"settlement-currency":"9"
}
}
}
}
and assigning it as var result = JSON.stringify(jsonObj); now result of string type has the converted JSON message.
From result, I need to get base-currency values
Any leads are appreciated.
Without further examples, I'm not sure if this is what you actually want, but as I understand:
You have this:
let x = '{k1: v1, k2: v2, k3: v3....}'
And you want to have this:
let object = {k1: v1, k2: v2,...}
The fastest way to do this would be using JSON.parse functionality:
let x = '{k1: v1, k2: v2, k3: v3....}';
let object = JSON.parse(x);
EDIT: In your specific example, you don't need to use JSON.stringify. You already have a JSON object, o access it like this:
let object = /*that parsed XML*/
let baseCurrency = object.OBJECT.TEMP.ROW['base-currency']; //this will give you the value as string
First use JSON.parse function to convert the string to JSON object.
const object1 =JSON.parse(jsonstr) ;
console.log(Object.keys(object1));
The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.
You can use JSON.parse function to convert the string to JSON object.
Hope the below example would help you get started.
const x = '{"key1":"value1","key2":"value2"}';
const json = JSON.parse(x);
console.log(json.key1);
console.log(json.key2);
Updates (based on changes in question)
The result you get from the fast-xml-parser is a JSON object. You need not convert it into a string using JSON.stringify. You can use that object directly and get the base-currency value.
See the code below.
const jsonObj = {
"OBJECT": {
"key": "postorder",
"type": "TEMP",
"TEMP": {
"ROW": {
"order-version-id": "1",
"layout-type": "2",
"order-no": "3",
"order-action": "4",
"estimated-price": "5",
"orig-price": "6",
"quantity": "7",
"orig-quantity": "8",
"quantity-type": "6",
"trade-currency": "7",
"base-currency": "8",
"settlement-currency": "9"
}
}
}
};
const baseCurrency = jsonObj.OBJECT.TEMP.ROW["base-currency"];
console.log(baseCurrency); // 8
This question already has answers here:
Get array of object's keys
(8 answers)
Closed 4 years ago.
I am currently trying to handle a GET request that returns a body in application/json structured like this:
{
"items": {
"item001": {"id":1234, "name": "name001"},
"item002": {"id":1235, "name": "name002"},
"item003": {"id":1236, "name": "name003"}
}
}
I'm trying to get an array of strings that looks like
array = ["item001", "item002", "item003"];
I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.
In fact, each time I try to even print the name of a single key, for example
var obj = JSON.parse({'whole json here'});
print(obj.items[1]);
I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!
You can do Object.keys.It will return an array of the keys of an object
var x = {
"items": {
"item001": {
"id": 1234,
"name": "name001"
},
"item002": {
"id": 1235,
"name": "name002"
},
"item003": {
"id": 1236,
"name": "name003"
}
}
}
var y = Object.keys(x.items);
console.log(y)
You can use Object.keys(). For Reference
var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
var result = Object.keys(obj.items);
console.log(result);
Object.keys will do that.
var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );
I'd like to get a key name of a JSON/JavaScript object as string. Maybe this is totally easy, but i just can't figure it out.
I have this object (simplified example, there are reasons to name the keys as strings):
var obj = {
"input1": {
"type": "input",
"value": "aaa"
},
"input2": {
"type": "checkbox",
"value": "bbb"
}
}
And now i would like to do something like this:
currentInputName = getTheNameOfThisAsString(obj.input1);
console.log(currentInputName); // output should be "input1"
currentInputName = getTheNameOfThisAsString(obj.input2);
console.log(currentInputName); // now output should be "input2"
I'm trying this with Object.keys() and Object.getOwnPropertyNames(), but both return type and value to me, so they are outputting the keys of the object specified, not the object name itself.
Use Object.keys() to access keys of your object.
var obj = { "input1": { "type": "input", "value": "aaa" }, "input2": { "type": "checkbox", "value": "bbb" } };
var keys = Object.keys(obj);
console.log(keys);
I am not sure what you are trying to accomplish, but I assume that you do not know the key, and thus you are sending object.key to your method.
How about changing the method to take the object and your object.key as parameters?
You call your method like this: getTheNameOfThisAsString(obj, obj.input1);
function getTheNameOfThisAsString(obj, subObject){
var keys = Object.keys(obj);
for(var key in keys){
if(subObject.value == obj[key].value){
return key;
}
}
}
From your comments, I was wondering if you can store your sub-object like this: currItem=obj["input1"], if that is the case, you already have the key as a string, and there is no need for an explicit method.
Here is an example:
var currItemName = "input1";
var currItem=obj[currItemName];
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.
How do you make JS think that a string is JSON ?
I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.
I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.
So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.
The string is as follows:
{
"data": [
{
"id": "id1",
"fields": [
{
"id": "name1",
"label": "joker",
"unit": "year"
},
{"id": "name2", "label": "Quantity"},
],
"rows": [ data here....
and closing braces..
var obj = JSON.parse(string);
Where string is your json string.
You can use the JSON.parse() for that.
See docs at MDN
Example:
var myObj = JSON.parse('{"p": 5}');
console.log(myObj);
I had the same problem with a similar string like yours
{id:1,field1:"someField"},{id:2,field1:"someOtherField"}
The problem here is the structure of the string. The json parser wasn't recognizing that it needs to create 2 objects in this case. So what I did is kind of silly, I just re-structured my string and added the [] with this the parser recognized
var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)
Hope it helps,
If anyone has a more elegant approach please share.
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
link:-
http://api.jquery.com/jQuery.parseJSON/
Simply use eval function.
var myJson = eval(theJsibStr);
convert the string to HashMap using Object Mapper ...
new ObjectMapper().readValue(string, Map.class);
Internally Map will behave as JSON Object
var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);
Let's us consider you have string like
example : "name:lucy,age:21,gender:female"
function getJsonData(query){
let arrayOfKeyValues = query.split(',');
let modifiedArray = new Array();
console.log(arrayOfKeyValues);
for(let i=0;i< arrayOfKeyValues.length;i++){
let arrayValues = arrayOfKeyValues[i].split(':');
let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
modifiedArray.push(arrayString);
}
let jsonDataString = '{'+modifiedArray.toString()+'}';
let jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
console.log(typeof jsonData);
return jsonData;
}
let query = "name:lucy,age:21,gender:female";
let response = getJsonData(query);
console.log(response);
`
JSON.parse() function will do.
or
Using Jquery,
var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );
JSON.parse() is your friend. Here's an example:
let obj = JSON.parse(yourString)
console.log(typeof obj); // prints 'object' assuming your string is correctly formatted