javascript json node w/ special char - javascript

so i am trying to parse some json yahoo finance data
i created this just for testing
but the special char ^ cannot be accessed...
how do you access the json node with special characters
i tried the bracket notation but did not work
with the ["^GSPC"] as suggested but get an error
get Unexpected token ^
var market={"^GSPC":{"symbol":"^GSPC","end":1604001600,"start":1603978200,close:[3330.69,3327.8,3308.83]}}
console.log(market.^GSPC)
any suggestions?

since json key is the special character, you should access using bracket notation, rather than dot.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties
var market={"^GSPC":{"symbol":"^GSPC","end":1604001600,"start":1603978200,close:[3330.69,3327.8,3308.83]}}
console.log(market["^GSPC"])

Instead of calling Object property using Object.key, use the square bracket Object[key] as follows.
You can call object property using key in two ways.
Object.key or Object[key].
var market={"^GSPC":{"symbol":"^GSPC","end":1604001600,"start":1603978200,close:[3330.69,3327.8,3308.83]}}
console.log(market["^GSPC"]);

Related

Why does JSON.parse("foo") fail but JSON.parse(' "foo" ') success?

When I try to JSON.parse("foo"), I get an Error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at <anonymous>:1:6
But, when I use JSON.parse('"foo"'), I can get the result as expected:
const value = JSON.parse('"foo"');
console.log(value)
So why does this happen?
You can find what makes valid JSON at json.org. JSON can represent null, booleans, numbers, strings, arrays and objects. For strings, they must be enclosed in double quotes.
JSON itself is a string format, so when you specify a string in JSON format, you need:
quotes to tell JavaScript you are specifying a string literal. Those quotes are not part of the string value itself; they are just delimiters.
double-quotes inside that string literal to follow the JSON syntax for the string data type.
So here are some examples of correct arguments for JSON.parse:
JSON.parse("true")
JSON.parse("false")
JSON.parse("null")
JSON.parse("42")
JSON.parse("[13]")
JSON.parse('"hello"')
JSON.parse('{"name": "Mary"}')
But not:
JSON.parse("yes")
JSON.parse("no")
JSON.parse("none")
JSON.parse('hello')
JSON.parse({"name": "Mary"})
Because the argument will be cast to string when it is not, the following will also work, but it is confusing (and useless):
JSON.parse(true)
JSON.parse(false)
JSON.parse(null)
JSON.parse(42)
This happens because JSON.parse() gives a value back by formatting the string given using the syntaxis to declare values in Javascript. Therefore using foo naked would be like casting an undefined variable.
Notice also that the notation uses double quotes " instead of single ones '. That's why JSON.parse('"foo"') works but JSON.parse("'foo'") won't.

parse json string with forward slashes - javascript

Looks pretty simple but I am unable to figure it out
var str="[{name:\"House\",id:\"1\"},{name:\"House and Land\",id:\"5\"},{name:\"Land\",id:\"6\"},{name:\"Terrace\",id:\"11\"}]";
JSON.parse(str.replace(/\s/g, "").replace(/\//g, ''));
I am unable to the convert above string(which comes from 3rd party website) to valid json so that I can iterate it on my side
error
VM5304:1 Uncaught SyntaxError: Unexpected token n in JSON at position 2
at JSON.parse (<anonymous>)
JSON requires the keys to be quoted. It appears that your keys are coming in unquoted. So add another .replace statement to insert the quote back in:
.replace(/(\w+):/g, '"$1":');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
Property names must be double-quoted strings; trailing commas are forbidden.
COMPLETE SOLUTION:
.replace(/(,|{)\s*(\w+)\s*:/g, '$1"$2":');

Get value of a key which starts with a number

I ran into a problem using the Pipedrive API. I tried to get some data using the below but it returned an error:
$.each(data.data, function(key,value) {
console.log(value.0d1df598a5539ab5b6b410b339dc9218e0acb091);
});
However this works:
$.each(data.data, function(key,value) {
console.log(value.person_name);
});
Why can't I get values of the keys that are complex strings generated by the Pipedrive system?
To retrieve what you require you would need to use bracket notation as the first character of the property identifier is an integer. Try this:
var value = {
'0d1df598a5539ab5b6b410b339dc9218e0acb091': 'foo bar'
}
console.log(value['0d1df598a5539ab5b6b410b339dc9218e0acb091']);
A possible explanation can be summarized in two part
Valid javascript variable(identifier names)
An identifier must start with $, _, or any character in the Unicode categories Uppercase letter (Lu), Lowercase letter, Titlecase letter (Lt), Modifier letter (Lm), Other letter (Lo), or Letter number (Nl).
In your case the identifier name start with an integer(0)
Property accessors
An key of an object in js can be retrieved either by using dot (.) notation or by using Bracket[]` notation
Square brackets notation allows use of characters that cannot be used with dot notation and also to retrieve an identifier which is not valid according to the first point.Beside it also allows to access properties containing special characters.
This is because js interpreter automatically converts the expression within square brackets to a string & retrieves the corresponding value.Actually
js evaluates the first complete expression with square brackets in a statement, runs toString() on it to convert it into a string and then uses that value for the next bracket expression, on down the line till it runs out of bracket expressions.
So dot notation has marginal upper-hand since it wont go throught he above process.
But it cannot be use it with a variable(or number).
It only allow to access explicit key name of a property
Since the identifier in your object identifiers's name starts with an 0 , bracket notation like value['0d1df598a5539ab5b6b410b339dc9218e0acb091'] will give it's value.

Json object with dash (-) character on element name

I'm parsing a json object that contains an element named data-config.
ex:
var video = data.element.data-config;
Whenever I parse this element I'm getting this error:
ReferenceError: config is not defined
The ReferenceError doesn't mention data-config but simply config.
Any idea why I'm getting this error?
Is this related with the dash (-) character?
Valid Characters
In general JavaScript, variable/function names can't contain -. They can only contain letters, $, and _ (Underscore)
So...
The error is coming because it's parsing:
var video is equal to data.element.data(valid) minus config
Solution
Because variables can't contain dashes, you need to use what I'm going to call String/Bracket Notation
data.element['data-config']
If you need to do more then one, do
data.element['data-config']['child']
I don't recommend using String/Bracket Notation when you don't have to, it's better practice.
You have to use [] notation when object properties contain special characters
var video = data.element['data-config'];

Accessing Json fields with weird characters

i have a json string im converting to object with a simple eval(string);
heres the sample of the json string:
var json = #'
"{ description" : { "#cdata-section" : "<some html here>" } }
';
var item = eval('('+json+')');
I am trying to access it like so
item.description.#cdata-section
my problem is that javascript does not like the # in the field name.. is there a way to access it?
item.description['#cdata-section']
Remember that all Javascript objects are just hash tables underneath, so you can always access elements with subscript notation.
Whenever an element name would cause a problem with the dot notation (such as using a variable element name, or one with weird characters, etc.) just use a string instead.
var cdata = item.description["#cdata-section"];
While the official spec for JSON specifies simply for chars to be provided as a field identifier, when you parse your JSON into a Javascript object, you now fall under the restrictions of a Javascript identifier.
In the Javascript spec, an identifier can start with either a letter, underscore or $. Subsequent chars may be any letter, digit, underscore or $.
So basically, the # is valid under the JSON spec but not under Javascript.

Categories