How to break down an array of objects within a string - javascript

I have some code that returns something like this:
body: '[
{
name: "name",
lastname: "lastname"
},
{
name: "name",
lastname: "lastname"
},
{
name: "name",
lastname: "lastname"
}
]'
Of course extracting the body is a simple object.body however, to get rid of the '' that wraps the array is just destroying me. I tried doing object.body.slice(1,-1) to get rid of them, it didnt work. I'm clearly not using the object properly.
How can I "extract" the array from within the body into a usable array?

It sounds like you want to evaluate the content of the string. Assuming whatever code building this string can't actually build JS objects to begin with, you can use eval or Function to generate the objects you need.
var data = eval(string);
Note that you must be sure that the source of the string is safe and reliable, otherwise you could be evaluating malicious code. There may also be performance consequences to using eval.
Using Function is a tiny bit safer, only because the code can not access your local variables. It should also avoid the performance costs of eval.
var data = Function("return (" + string + ");")();
Same warning about malicious code though.
If the string data was valid JSON, you could use JSON.parse, but it isn't, so you can't. To avoid security issues, either have the source provide valid JSON data, or write your own minimal parser to parse the data.

With a valid JSON string, you could just parse the string for an object with JSON.parse, if you have .
array = JSON.parse(string);

You can use split function and then take the first element, let me say
var a = '[{name: "name",lastname: "lastname"},{name: "name",lastname: "lastname"},{name: "name",lastname: "lastname"}]';
var s = a.split("'");
s[0] will return you the desired result

Related

Javascript object with arrays to search param style query string

Looking for clean way to convert a javascript object containing arrays as values to a search param compatible query string. Serializing an element from each array before moving to the next index.
Using libraries such as querystring or qs, converts the object just fine, but handles each array independently. Passing the resulting string to the server (which I cannot change) causes an error in handling of the items as each previous value is overwritten by the next. Using any kind of array notation in the query string is not supported. The only option I have not tried is a custom sort function, but seems like it would be worse than writing a custom function to parse the object. Any revision to the object that would generate the expected result is welcome as well.
var qs = require("qs")
var jsobj = {
origString:['abc','123'],
newString:['abcd','1234'],
action:'compare'
}
qs.stringify(jsobj,{encode:false})
qs.stringify(jsobj,{encode:false,indices:false})
qs.stringify(jsobj,{encode:false,indices:false,arrayFormat:'repeat'})
Result returned is
"origString=abc&origString=123&newString=abcd&newString=1234&action=compare"
Result desired would be
"origString=abc&newString=abcd&origString=123&newString=1234&action=compare"
I tried reorder your json:
> var jsobj = [{origString: 'abc', newString: 'abcd' }, {origString: '123',
newString: '1234' }, {action:'compare'}]
> qs.stringify(jsobj,{encode:false})
'0[origString]=abc&0[newString]=abcd&1[origString]=123&1[newString]=1234&2[action]=compare'
But I don't know if this is a good alternative for your problem.
Chalk this up to misunderstanding of the application. After spending some more time with the API I realized my mistake, and as posted above by others, order does no matter. Not sure why my first several attempts failed but the question is 'answered'

Why can't commas be in Javascript object keys?

This is an odd thing to ask I am aware, but I am very much a newbie and can't seem to wrap my head around this. I have a Javascript object sent to me via firebase that looks like this:
var blob = {
matt#email,com: { //notice the comma because periods are illegal in keys
email: "matt#email.com" //actual email with period
name: "Matt Sanford"
pic: "https://lh3.googleusercontent.com/-LeQrq-_KjJE/AAAAAAAAAAI/AAAAAAAAAoI/4l6r2HNdock/photo.jpg"
provider: "google"
uid: "0000000000000000"
}
}
}
I am trying to access the inner most tree via the console like so: console.log(blob.matt#email,com) //throws an error because of an invalid token
even though it should return the object with email, name, etc.
However when I tried the same structure like so:
var blob = {foo: {bar: true} }
console.log(blob.foo) //output '{bar: true}'
There are two things I am wondering, is having the initial key with the modified email illegal because of the commas or is there not a way to read such a key in javascript? Recommendations are appreciated because I am just learning as I go along here.
Update
How would I go about accessing the keys dynamically? Clearly it would be impossible to input each key dynamically. How would I read it without knowing what exactly the key name is?
What you posted is not a json object, it's a javascript object. JSON would have all its keys quoted.
Comma's are definitely allowed, but you cannot use the standard obj.property syntax like this:
console.log(blob.matt#email,com)
You must do:
console.log(blob['matt#email,com']);

convert string to dynamic array with variables in javascript

How would I take a string (that I got from a page using jQuery's text()) such as:
var myData = "[{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}]"; //this is a string :(
And turn it into the actual javascript object that I need, so for example:
var myObject = [{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}];
So 'name' and 'data' will be non-dynamic variables, however names value, the data array and the length of myObject will be dynamic.
Not really sure where to start with this one. I am guessing that I will have to do a whole lot of spliting and looping, but I am open to suggestions.
Well, it can be done very easily:
var myObject = eval(myData);
However, you should be aware of the risks of the eval function. As it runs the value as a Javascript expression, it would also run any harmful code that would be in the string, so you should only use it when you have full control over what's in the string.
If you could change the format to be JSON, you could safely parse it without risks of code injection:
var myData = '[{"name":"xxx","data":[1,2,3,4,5]},{"name":"yyy","data":[5,4,3,2,1]}]';
var myObject = $.parseJSON(myData);
You mean,
var myObject = eval('(' + myData + ')');
?
EDIT
Its major con is that you can put any javascript code (not only JSON) to eval (Chrome's F12 lets anyone to exploit this). AS you are using jQuery, best choice will be
var myObject = $.parseJSON(myData);
for cross browser compatibility.
$.parseJSON
Takes a well-formed JSON string and returns the resulting JavaScript
object. Passing in a malformed JSON string may result in an exception
being thrown. For example, the following are all malformed JSON
strings:
{test: 1} (test does not have double quotes around it).
{'test': 1} ('test' is using single quotes instead of double quotes).

Why can't I access JSON objects by key in JavaScript?

This is my JSON object:
{ text: 'stuff',
user: 'user1
}
when I run a typeof jsonObj, I get object. When I run an jsonOb.length, I get undefined. When I tried to access the text property via console.log(jsonObj.text), I get undefined.
So how can I properly access everything in JavaScript?
I don't want to use jQuery as this is all node.js programming so it's serverside.
UPDATED - full JSON
{ text: '#junk_666 おかえりか',
user:
{ display_name: 'mono',
screen_name: 'monochrm',
klout_score: null,
location_str: '画面の前',
utc_offset: '32400' },
venue_id: 1304409836517,
match_type: 'twitter',
tweet_id: '116494264137023489',
created_at_unix: 1316609371,
meta:
{ matchedPhrase: 'junk',
venueName: 'deletemepls really long name' },
tags: [ '' ],
indexed_at_unix: 1316609416 }
The json seems to be invalid
{
"text": "stuff",
"user": "user1"
}
I copied and pasted your object into a FireBug console and it recognized it.
If you need to count the number of key/value pairs, you can use a function such as this one to do it:
function numMembers(o) {
var i=0;
for (a in o) {
i++;
}
return i;
}
You should be able to access the value of the text property via jsonObj.text. Are you sure that your object is being referenced by jsonObj? Also, can you access the values for simpler objects such as the ones mentioned in other posts if you create them? Furthermore, does anything work if you use only ASCII characters? For some reason, it might not be handling some of the non-Latin characters properly.
First, what you have is not JSON because JSON requires property name to be in double quotes. It is a valid JavaScript object literal though, so I'll assume that's how you're using it.
Secondly, JavaScript objects in general do not have a length property. Arrays do.
There's no problem with your object literal so there must be some other problem elsewhere in your code.
Try this:
{ text: 'stuff',
user: 'user1'
}
You left off an apostrophe.
Now that you've posted your full JS code (that's not JSON, as #josnidhin points out)... works fine in jsFiddle. http://jsfiddle.net/Rs9R4/ I don't believe a JS Object has .length, just Arrays.

Problem parsing JSON

I encounter problems tring to consume a third party web servive in JSON format. The JSON response from the server kinda looks like this:
{
"ID":10079,
"DateTime":new Date(1288384200000),
"TimeZoneID":"W. Europe Standard Time",
"groupID":284,
"groupOrderID":10
}
I use JavaScript with no additional libs to parse the JSON.
//Parse JSON string to JS Object
var messageAsJSObj = JSON.parse(fullResultJSON);
The parsing fails. A JSON validatior tells me, "new Date(1288384200000)" is not valid.
Is there a library which could help me parse the JSON string?
Like others have pointed out, it's invalid JSON. One solution is to use eval() instead of JSON.parse() but that leaves you with a potential security issue instead.
A better approach might be to search for and replace these offending issues, turning the data into valid JSON:
fullResultJSON = fullResultJSON.replace(/new Date\((\d+)\)/g, '$1');
You can even go one step further and "revive" these fields into JavaScript Date objects using the second argument for JSON.parse():
var messageAsJSObj = JSON.parse(fullResultJSON, function (key, value) {
if (key == "DateTime")
return new Date(value);
return value;
});
Here's an example: http://jsfiddle.net/AndyE/vcXnE/
Your example is not valid JSON, since JSON is a data exchange technology. You can turn your example into a Javascript object using eval:
var almostJSON = "{
"ID":10079,
"DateTime":new Date(1288384200000),
"TimeZoneID":"W. Europe Standard Time",
"groupID":284,
"groupOrderID":10,
}";
and then evaling it:
var myObject = eval('(' + almostJSON + ')');
Then, myObject should hold what you're looking for.
Note that functions are not allowed in JSON because that could compromise security.
try var obj = eval('(' + fullResultJSON + ')'); and you'll have the object like Pekka said. Don't forget to use the extra '()' though. And indeed json should have both property and value enclosed in quotes.
Parsing fails because all you can parse in a json object are null, strings, numbers, objects, arrays and boolean values so new Date(1288384200000), cannot be parsed
You have also another problem, last property shouldn't have the trailing comma.

Categories

Resources