I have the following JSON output and I need to access the variable TN_TEXTO. How can I access it?
["data", [
["notification",
{
"TN_CODIGO": "3",
"TN_TP_CODIGO": "1",
"TN_TEXTO": "dddddddddddd",
"TN_DATA": "1325708743",
"TN_LINK": "",
"TN_READ": "0"
}]
]]
Thanks in advance!
Use JSON.parse to convert a string to an object. Then you can use JavaScript syntax on it.
var object = JSON.parse(string);
alert(obj[1][0][1].TN_TEXTO);
Live example
myvar = ["data", [
["notification",
{
"TN_CODIGO": "3",
"TN_TP_CODIGO": "1",
"TN_TEXTO": "dddddddddddd",
"TN_DATA": "1325708743",
"TN_LINK": "",
"TN_READ": "0"
}]
]]
alert(myvar[1][1]["TN_CODIGO"]); // is 3
If you're using JSON string:
var json = '["data", [["notification", { "TN_CODIGO": "3", "TN_TP_CODIGO": "1", "TN_TEXTO": "dddddddddddd", "TN_DATA": "1325708743", "TN_LINK": "", "TN_READ": "0" }] ]]';
var array = JSON.parse(json);
alert(array[1][0][1]["TN_TEXTO"]);
If you have already parsed the string just:
alert(array[1][0][1]["TN_TEXTO"]);
Related
Hi iam finding the best way to add a string inside the given object.Any help would be appreciated
my String is 'created'
Down Below Is My Data
{
"id": "222",
"list": [
{
"name": "Tony",
}
],
iam trying to insert 'created' in the data like this
{
"id": "222",
"list": [
{
"name": "Tony",
"type":"created"
}
]
The string you've provided looks a lot like JSON data. You can convert a JSON string to an actual javascript object by using the JSON.parse(string) method.
With this object we then can query it's list property - which in your case is an array of objects - and add a new property type to each of the arrays elements. The final step is converting the object back to a JSON string using the JSON.stringify(object) method.
Here's an example:
let str = `{
"id": "222",
"list": [
{
"name": "Tony"
}
]
}`;
let data = JSON.parse(str);
data.list.forEach(element => {
element.type = "created";
});
str = JSON.stringify(data);
console.log(str);
const myObj = {
"id": "222",
"list": [
{
"name": "Tony",
}
],
};
myObj.list[0].type = "created";
This is the way you can do this. But you'd better use secified index of list items;
const index = 0; // Or any other way to get this
myObj.list[index].type = "created";
I need to extract json from a particular string which looks like this:
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]
I have tried this but could not extract it .
var regex=cookies.match(/{"seed":(\w|\W)*"channel":(\w|\W)*}/);
What is the solution I could use?
Thanks in advance:)
If you know there is only a single plain JSON object like this in the string, you can use this regex to capture the curly braces and everything in between:
const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found
This is no way guarantees the string is valid JSON. So if you want to run JSON.parse on the result, be aware it will throw an error if the string is invalid.
For the loglocale:
let dataJSON = `
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]`
then:
let string = dataJSON.substring(
dataJSON.indexOf("loglocale=") + 10,
dataJSON.lastIndexOf("; regStatus")
)
JSON.parse(string);
{
"3": {
"id": "3",
"ocena_ocena": "2",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "31.12.2015."
},
"1": {
"id": "1",
"ocena_ocena": "5",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "22.12.2015."
}
}
I am using ajax to get this JSON. I tried parsing it like this:
request.done(function(response) {
alert(response.ocena_ocena);
});
Could someone please help me with this?
I also need to know how can I do a foreach statement with json?
Since your JSON represents a JavaScript object, you should include the attribute name (if we consider JavaScript object to be a map, then, we need to use the key).
Try
response["1"].ocena_ocena
or
response["3"].ocena_ocena
Since you are returning a JSON object from server instead of an array, to iterate over its properties, you could do
for (var i in response) {
console.log(response[i].ocena_ocena);
}
or
Object.keys(response).forEach(function f(e) {console.log(response[e].ocena_ocena)})
If you could modify your server side code to return JSON that looks like this,
[
{
"id": "3",
"ocena_ocena": "2",
...
},
{
"id": "1",
"ocena_ocena": "5",
...
}
]
then you could iterate over it more easily
response.forEach(function f(e) {console.log(e.ocena_ocena)})
I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']
I have this multiple set of data as array
data = [{"id": "1", "name" : "abc", "key1" : "value12 }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
I need to get this data using jQuery
json = $.parseJSON(data);
but how do I access the parsed JSON data? json.id shows the result as undefined.
Thanks
Update : Sorry I fixed the above example JSON I gave, I just quickly typed it by myself and it's not the original json I'm having trouble with. I just gave it to give an idea about the problem that I was having. Thanks for the answers :)
It isn't JSON. It isn't even JavaScript.
If you fix the syntax errors (such as the missing quotes and the missing commas between the array items) then it is an array literal (containing object literals which contain …). Don't parseJSON it (you use that on JSON texts stored in JavaScript strings).
Since it is an array. It doesn't have an id. It has a number of numerical indexes.
var someObject = data[0];
The objects stored on those indexes have ids.
var id = someObject.id;
Your json is invalid. ',' are missing between objects.
Suppose if json is :
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }]
Then you can access 'id' element using this :
data[0].id
Try this:
var data = '{"id": "1", "name" : "abc", "key1" : "value12" } , {"id": "2", "name" : "cde", "key2" : "value2"}';
var obj = JSON.parse('[' + data + ']');
alert(obj[0].id);
Here is demo
Your json is invalid,
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
Retrive using:
var id = data[0].id;
console.log(id);