JavaScript: Init Array from string - javascript

A beginners question: I am trying to create and init an Array of users using the following string as initial data in JavaScript:
{ "user": {"notes": [{ "text": "Hello ", "date": "12\/1\/2013 5:01:36 AM", }], "name": "Alex"} }, { "user": { "notes": [{ "text": "Hi ", "date": "12\/1\/2013 5:15:19 PM"}, { "text": "It is me", "date": "12\/1\/2013 6:23:54 PM"}], "name": "Anna"} }
Is it possible in general (how?) or am I completely getting it wrong?

Your JSON is invalid. It contains a syntax error (possible a typo in the question) - an invalid comma after the first user's date, and it is also a list of objects that are not enclosed with the array syntax [].
The corrected json and example of parsing is:
Demo
var json = '[{ "user": {"notes": [{ "text": "Hello ", "date": "12\/1\/2013 5:01:36 AM" }], "name": "Alex"} }, { "user": { "notes": [{ "text": "Hi ", "date": "12\/1\/2013 5:15:19 PM"}, { "text": "It is me", "date": "12\/1\/2013 6:23:54 PM"}], "name": "Anna"} }]';
// ^ the list of objects need to be enclosed with []
var users = JSON.parse(json);
for(var i=0; i<users.length; i++)
{
console.log(users[i].user.name);
}

Generally speaking, you got that string using an ajax call, right?
and you can convert that string to an javascript object using JSON.parse(strToBeConverted)
in all modern browsers.
What if there is no such built-in JSON object? Do as below says,
1. import JS downloaded from this site which is created by Douglas Crockford,
2. use JSON.parse to do your business.

Make sure the JSON code is valid, use JSONLint for that. There is an error in your code, I fixed it in the code below.
Use JSON.parse() to transfer it to an object.
To be compatible to all browsers make sure you have json2 included as well (not all browsers have the JSON object to call the JSON.parse function).
As mentioned by Anthony the result is not an array but an object. To iterate over the user list see the jsfiddle or the example below.
EXAMPLE
var str = "[{user:...";
var userList = JSON.parse(str);
for(var i in userList){
var user = userList[i].user;
document.write(user.name + "<br/>");
}
CORRECTED JSON
[
{
\"user\": {
\"notes\": [
{
\"text\": \"Hello \",
\"date\": \"12/1/2013 5:01:36 AM\"
}
],
\"name\": \"Alex\"
}
},
{
\"user\": {
\"notes\": [
{
\"text\": \"Hi \",
\"date\": \"12/1/2013 5:15:19 PM\"
},
{
\"text\": \"It is me\",
\"date\": \"12/1/2013 6:23:54 PM\"
}
],
\"name\": \"Anna\"
}
}
]

Related

How to convert long string to list of objects

How can I convert the following into a list of objects with javascript.
data:
{"_id":{"$oid":"5d96f2d3db90fded9f3fa2d1"},"name":"Audi","price":52642},{"_id":{"$oid":"5d96f2dedb90fded9f3fa2d2"},"name":"Mercedes","price":57127},{"_id":{"$oid":"5d96f304db90fded9f3fa2d3"},"name":"Skoda","price":9000},{"_id":{"$oid":"5d96f368db90fded9f3fa2d4"},"name":"Volvo","price":29000},{"_id":{"$oid":"5d96f370db90fded9f3fa2d5"},"name":"Bentley","price":350000},{"_id":{"$oid":"5d96f378db90fded9f3fa2d6"},"name":"Citroen","price":21000},{"_id":{"$oid":"5d96f37fdb90fded9f3fa2d7"},"name":"Hummer","price":41400},{"_id":{"$oid":"5d96f389db90fded9f3fa2d8"},"name":"Volkswagen","price":21600}
When I do typeof on the data I get string. What I am trying to do is create a list with an entry for every object. I tried JSON.parse but it errors on the commas between the curly braces.Thank you.
For that particular string – comma-separated JSON objects – you can wrap it in array brackets [] and parse it:
var data = `{"_id":{"$oid":"5d96f2d3db90fded9f3fa2d1"},"name":"Audi","price":52642},{"_id":{"$oid":"5d96f2dedb90fded9f3fa2d2"},"name":"Mercedes","price":57127},{"_id":{"$oid":"5d96f304db90fded9f3fa2d3"},"name":"Skoda","price":9000},{"_id":{"$oid":"5d96f368db90fded9f3fa2d4"},"name":"Volvo","price":29000},{"_id":{"$oid":"5d96f370db90fded9f3fa2d5"},"name":"Bentley","price":350000},{"_id":{"$oid":"5d96f378db90fded9f3fa2d6"},"name":"Citroen","price":21000},{"_id":{"$oid":"5d96f37fdb90fded9f3fa2d7"},"name":"Hummer","price":41400},{"_id":{"$oid":"5d96f389db90fded9f3fa2d8"},"name":"Volkswagen","price":21600}`;
var parsed = JSON.parse(`[${data}]`);
Then parsed will be an array of 8 entries:
[
{
"_id": {
"$oid": "5d96f2d3db90fded9f3fa2d1"
},
"name": "Audi",
"price": 52642
},
{
"_id": {
"$oid": "5d96f2dedb90fded9f3fa2d2"
},
"name": "Mercedes",
"price": 57127
},
{
"_id": {
"$oid": "5d96f304db90fded9f3fa2d3"
},
"name": "Skoda",
"price": 9000
},
...

How to parse multi-line JSON response to exact a particular key's value?

I'm trying to parse a multi-line JSON response to get a value for a key using JavaScript. I read we can't parse multi-line json, how I can achieve getting "Created" value from below json?
I tried converting the JSON to string and used replace to converting multi-line to single line with \n as deliminator. -- Unable to replace multi-liner text.
I tried extracting index of mischief key value and remove from the string -- Syntax error.
var v1 = {
"data": {
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON:API paints
my bikeshed!",
"body": "The shortest article. Ever.",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z"
},
"relationships": {
"author": {
"data": {
"id": "42",
"type": "people"
}
}
}
}
};
alert(result.data.attributes.created);
My expectation is to get 2015-05-22T14:56:29.000Z as output.
In your example i see syntax error
Try to change string definition "" to ``
var v1 = {
"data": {
"type": "articles",
"id": "1",
"attributes": {
"title": `JSON:API paints
my bikeshed!`,
"body": "The shortest article. Ever.",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z"
},
"relationships": {
"author": {
"data": {
"id": "42",
"type": "people"
}
}
}
}
};
console.log(v1.data.attributes.created)
In case of new line you can replace all the new lines and then parse
the JSON.
Each OS generate different newline characters you need to
be aware of that while replacing newline characters.
var v1 = `{
"data": {
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON:API paints
my bikeshed!",
"body": "The shortest article. Ever.",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z"
},
"relationships": {
"author": {
"data": {
"id": "42",
"type": "people"
}
}
}
}
}`;
var result = v1.replace(/(?:\r\n|\r|\n)/g, '');
var resultObj = JSON.parse(result);
console.log(resultObj.data.attributes.created);

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

get string of elements by name

I'm newbee in JS so i need your help.
I have this JSON code :
{
"data": {
"people": [
"get_my_obj": [
{
"yearcome": 2006,
"email": "email1#test.com",
"came": "1.12",
"name": "Alex "
},
{
"yearcome": 2010,
"email": "email2#test.com",
"came": "1.12",
"name": "John"
},
{
"yearcome": 2012,
"email": "email3#test.com",
"came": "1.12",
"name": "Max"
}
]
}
}
How i can get string of elements with emails?
For example var a = email1#test.com;email2#test.com;email3#test.com;
Thats really hard for me because if i have only 2 objects so string must show 2 emails if 3 objects show 3 emails.
Please help me find the way how to do it
var s = { data: ....};
var mails = s.data.people.get_my_obj.map(function (e) { return e.email; }).join(';');
console.log(mails);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Iterate through nested Javascript Objects from API response

I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);

Categories