JSON.parse on array of JSON strings not doing as expected - javascript

I'm new to javascript so learning how some of this stuff works.
I have a string that looks like: ["{\"name\":\"name\"}","{\"name\":\"Rick\"}"]
If I JSON.parse() that shouldn't it return an array of objects that have a property of name?
What I get is 2 elements in an array but they are just the JSON strings. They are not objects with property name. What am I missing?
[EDIT]
I was calling stringify() on the object and then passing it to the array instead of just passing the object as is to the array. Then I stringify() the array. I was stringifying a stringify which caused it to put the escape characters :)

If I JSON.parse() that shouldn't it return an array of objects that have a property of name?
No, it looks like the JSON defines an array with two strings in it.
This is the JSON for an array with two strings in it:
[
"{\"name\":\"name\"}",
"{\"name\":\"Rick\"}"
]
In JavaScript string literal form, that's '["{\"name\":\"name\"}","{\"name\":\"Rick\"}"]'.
This is the JSON for an array with two objects in it:
[
{
"name": "name"
},
{
"name": "Rick"
}
]
In JavaScript string literal form, that would be '[{"name":"name"},{"name":"Rick"}]'.

I guess its sholuld come as:
"[{\"name\":\"name\"},{\"name\":\"Rick\"}]"

If you lose the (escaped) quotes around the root elements you might get what you want.
E.g. something like
"[{"name":"name"},{"name":"Rick"}]"

Related

How to convert JSON array property value from arrays to keys

I am a beginner programmer trying to convert JSON array property value from arrays to keys.
From
..,"searchResult":[{"itemId":["123"],"title":["abc"],..}]
to
..,"searchResult":[{"itemId":"123","title":"abc",..}]
Full original JSON result here with search result highlighted
the JSON array is being received in this code
//function to retrieve JSON arrays
function _cb_findItemsByKeywords(root) {
//Navigates and assigns variable "items" into the property, item
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var a = (items);
//assigned variable a to the array
}
Question: How do I remove the square brackets and check my array a?
EDIT:
Sorry for the confusion, My goal is to combine this array with [..] with another array without [..] before appending the properties to a table.
My plan:
If I understand your question correctly, you wish to convert a JSON array into a Javascript object, since altering JSON property values to keys wouldn't be valid JSON.
To convert JSON array into Javascript object, in pure Javascript you do:
JSON.parse(yourJSONgoeshere);
Docs and examples here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Hope it helps.

array and object confusion in json

what is the different between is
var json = [{
'id':1,
'name':'John'
}]
and
var json = {
'id':1,
'name':'John'
}
my understanding is that in code one json is an array, which means we can have multiple object which contains property of id and name. But for the second one it's an object. Is it?
and how about this one
var json = ['id':1,'name':'John']
compare to code one?
Nothing is valid JSON in your case.
The first one is an array of native javascript objects.
The second one is a javascript object.
The last one isn't valid and will throw error. It is syntactically wrong.
Use JSON.stringify() on javascript arrays or objects to make it a valid JSON.
You understanding about code one and code two are correct.
But however, the json syntax about code one and two is error. Because each json field must use double quotes, not single quotes.
so code one and code two must be written like this:
[
{
"id": 1,
"name": "John"
}
]
and
{
"id": 1,
"name": "John"
}
Now code three's syntax is error! If you want to mean an array, it must be var json = []; json['id']=1; json['name']='John'; or an object var json={'id':1,'name':John'}
JSON is a format, i.e. a way to encode Javascript objects to a sequence of characters.
Once you have a sequence of characters you can store it on disk or send it over a network and later rebuild the objects described in the sequence of characters.
You cannot encode every possible Javascript value in JSON, but only
strings
numbers (excluding NaN and infinity)
null
arrays
other objects (just the fields with values that can be encoded, not the constructor or methods)
Also, the data structure must be a tree. (You get an error if it has loops, and shared sub-trees are not detected and will be duplicated when rebuilding from JSON.)
Moreover JSON doesn't support is the presence of other fields in arrays (something that is possible in Javascript, because arrays are objects). For JSON, you have either an array or an object.
The values in your first two examples can be converted to JSON, but there are additional requirements in the format specifications. (E.g. object field names must be double quoted.)
Your last example instead is not a valid JSON string.
When you see "JSON object" or "JSON value" you must read it as "object encoded in JSON". JSON is a format, more or less like XML.

Access JSON object to get Resource Bundle key/value pair

I know how to access key value pair from JSON object but in my case, the resource bundle keys are mapped to values.
e.g.
var json = {"label.name.first":"foo","label.name.second":"bar"};
Here json.label.name.first doesn't give me "foo".
Can someone help me with this?
Due to using the period character (.) in the key name, you need to use the [] notation to access its value.
console.log( json['label.name.first'] );
Additionally, you have a JavaScript object, not JSON.
The difference between a JavaScript object or JSON is that JSON is always a string. Secondly, JavaScript objects don't require the same quote standards on the key names.
If you just consider the string below, then yes it can be considred JSON (this is why if you paste it into a JSON parser, it tells you it's valid JSON):
{"label.name.first":"foo","label.name.second":"bar"}
However, if you assign that directly to a JavaScript variable then you have a JavaScript object literal, not JSON. This is because JSON is also a valid JavaScript object/array literal when it is not contained in a string:
var obj = {"label.name.first":"foo","label.name.second":"bar"};
If you were to use it as a string, then it is JSON:
var json = '{"label.name.first":"foo","label.name.second":"bar"}';
// json is a string, so it's JSON
var obj = JSON.parse(json); // parse the JSON into an object
The confusion is quote common because the JSON format is very similar to the format of JavaScript object and array literals.
Do this:
json["label.name.first"]
However, I think you are misunderstanding the . notation.
And BTW your json isn't a JSON, it is a javascript object and not its notation.
It's json["label.name.first"] that would get you "foo". Since your property's name contains characters that cannot be used in variable names.
If you're expecting to access these properties using the syntax json.label.name.first then your JSON needs to be:
var json = {
"label":{
"name":{
"first":"foo",
"second":"bar"
}
}
}
This is not right way to create object, you should create one like this.
var json={"label":{"name":{"first":"foo","second":"bar"}}};
it will also work as json string

How to parse/use this JSON in Javascript

I have a variable with the following in my code:
{
"Rows":
[
{
"New":1,
"CachedNumberType":0,
"Date":1327479615921,
"Type":2,
"Number":"123456",
"Duration":1
}
]
}
I think it's JSON, how do I parse it? (E.g., with json2.js?) Or how do I use it in my JavaScript?
var jsonObj = JSON.parse(jsonString);
You've said that when you try JSON.parse on the variable containing the "JSON" that it says it can't parse it. Could it be that it's already deserialized? Or maybe it was never JSON at all? For instance, what you quoted, in JavaScript source, is an object literal containing an array literal containing another object literal; no JSON in sight.
If you do console.log(x.Rows[0].Date);, where x is the variable you were trying to pass to JSON.parse, do you see the date value?
A lot of people confuse JSON and JavaScript literal syntax, because JSON is a textual format derived from JavaScript literal syntax. I suspect that's what's happening here.

Returning number of elements of JSON object

I need to iterate over every element in a JSON object, and I'm having trouble working out a way to count the number of elements in that object so I can use a for loop to iterate. Here's my object:
this.worldData =[
{"0":{"1":"0", "2":"0"},
"1":{"1":"0", "2":"0"},
"2":{"1":"0", "2":"0"}}
];
And what I'm trying:
alert(this.worldData.length);
Problem is, it always returns 1, no matter how many elements I put into the JSON object.
Do you have control over the JSON data? The length is returning 1 because there is only one element in the array. This is because of the way the JSON data is structured here. If you want something easier to iterate over, you would want something like this:
this.worldData = [
{"1":"0","2":"0"},
{"1":"0","2":"0"},
{"1":"0","2":"0"}
]
Note that objects (denoted with {}) don't have a length property, while arrays (denoted with []) do.
You're wrapping all of your objects inside a single object (the first and last curly braces). Try this:
this.worldData =[
{"0":{"1":"0", "2":"0"}},
{"1":{"1":"0", "2":"0"}},
{"2":{"1":"0", "2":"0"}}
];
jsFiddle example.

Categories