JSON validation - javascript

I'm trying to work with json-framework on iPhone to parse a json string.
When I'm calling this method:
NSDictionary *dictionary = [jsonString JSONValue];
I'm getting the error:
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key:
Options\" UserInfo=0x4b5f390 {NSUnderlyingError=0x4b5f320 \"Expected value while
parsing array\", NSLocalizedDescription=Object value expected for key: Options}"
According to this json validator [1]: http://www.jsonlint.com// my json is not valid. But is that so??
My json string looks like this:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary",
}
}
* Edited Json: (still brings up an error)
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary"
}
]
}

Your JSON is not valid.
It's because you can't create object instances within JSON. It's not a valid value.
new Date(2011, 0, 7, 12, 30, 0)
And you missed the closing array bracket. Everything else is ok.

remove the comma after ...Binary"
add a ] between the two } }.
Date cant be used like this, see How do I format a Microsoft JSON date? and http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_sidebarb
This is valid:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": "new Date(2011,0,7,12,30,0)",
"Type": "Binary"
}
]
}

You can't instantiate Date objects (or any objects) in a JSON string.
You need to have whoever's responsible for the code that emits this JSON change it to emit valid JSON. They're putting out something now that can't work with any JSON parser. Maybe they have a customized JSON consumer that can handle such things, but this isn't standard JSON.
If I were you, I'd have them put the string of the current date into that field (so: "2011-07-01 12:30:00") and then parse that in your obj-cusing NSDateFormatter.
If whatever puts out that JSON isn't something you can change, you can always modify it locally before feeding it to the JSON library. It's just a string, nothing magical.

Related

How can I extract data from a JSON file using javascript?

I have this simple variable which I am trying to extract data from. I've parsed it successfully to a json object and tried to print a value based on it a key. But all it says is "undefined". This example I provided is actually a snippet of the json I am trying to manipulate. The full file is actually a json object where one of the elements contains an array of many json objects (these are the ones I ultimately have to access). I have watched countless tutorials and have followed them exactly, but none seem to have this issue.
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
JSON.parse(x);
console.log(x.status);
Can anybody suggest something I may be doing wrong? Thank you!
JSON.parse Return value
The Object, Array, string, number, boolean, or null value
corresponding to the given JSON text. - MDN
You have to assign the parsed result to some variable/constant from where you can use later that parsed value and then use that variable to extract data as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
const parsedData = JSON.parse(x);
console.log(parsedData.status);
or you can directly get value one time after parsed as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
console.log(JSON.parse(x).status);

Json to javascript dictionary

I have JSON data in the following structure, and I'm trying to parse it in order to work with the data using javascript.
JSON Data
{
"FirstItem": {
"id": 1,
"type": "foo",
"colours": ["blue", "black", "green"],
"reviews": {
"positive": ["The best", "unbelievable", "Awesome"],
"negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"],
"neutral": ["OK", "Meh"]
}
},
"SecondItem": {
"id": 2,
"type": "bar",
"colours": ["red", "white", "yellow"],
"reviews": {
"positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"],
"negative": ["Terrible", "Shocking", "abysmal"],
"neutral": ["OK", "Standard", "Vanilla"]
}
}
}
I am trying to parse this using JSON.parse(), however this returns the following error:
JSON.parse: unexpected character at line 1 column 2 of the JSON data
I have previously worked with this same JSON structure using C#, and had to deserialise this into a dictionary - information can be found on this post
Question
How can I parse this JSON into a javascript object, which will allow me to loop and evaluate each item?
JSON is Javascript Object with double quoted key like what you have in sample. So you don't need to parse it again, see this for explanation. You can access data from it using its key or if in case you want to get reviews from SecondItem, you can access it with :
SecondItem.reviews
or
SecondItem['reviews']
Apparently you are trying to parse an already parsed object
x = {A:1}; // A javascript object
JSON.parse(x); // Error
this happens because JSON.parse will convert the object to a string first, getting "[object Object]" and then will try to parse this string.

Display json object in angularjs codemirror

I have a json object and want to display it on codemirror using angularjs codemirror but it got an error saying ui-codemirror cannot use an object or an array as a model. Then I tried to convert the object into string using JSON.stringify, the string does not format nicely in codemirror. Anyone can help me to figure out how to make my code in formatted nicely in codemirror?
Thanks
ex:
//inside javascript
$scope.code = {
"name": "user1",
"id": "34",
"value": [3, 5, 4]
};
$scope.editorOptions = {
lineWrapping : true,
lineNumbers: true,
mode: 'application/json',
};
//inside html
<ui-codemirror ui-codemirror-opts="editorOptions" ng-model="code"></ui-codemirror>
It returns an error for this: ui-codemirror cannot use an object or an array as a model
if I change to JSON.stringify($scope.code), code mirror display like this:
{"name":"user1","id":"34","value":[3,5,4]}
However, I want it to display as this:
{
"name": "user1",
"id": "34",
"value": [3, 5, 4]
}
Any help?
Thanks
You can specify the indentation:
$scope.codeView = JSON.stringify($scope.code, null, 4);
Live example

Parse decodeURIComponent JSON string with Python

I have a "deep" JSON string that I need to pass as GET vars in a URL. It looks like the following:
{
"meta": {
"prune": true,
"returnFields": ["gf", "gh", "gh", "rt"],
"orient": "split"
},
"indicators": [{
"type": "beta",
"computeOn": "gf",
"parameters": {
"timeperiod": 5,
"nbdevup": 2,
"nbdevdn": 2,
"matype": 0
}
}, {
"type": "alpha",
"computeOn": "gf",
"parameters": {
"timeperiod": 30
}
}]
};
When encoding using jQuery.param, the result is as follows:
var recursiveEncoded = jQuery.param(body);
console.log(recursiveEncoded);
meta%5Bprune%5D=true&meta%5BreturnFields%5D%5B%5D=gf&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=rt&meta%5Borient%5D=split&indicators%5B0%5D%5Btype%5D=beta&indicators%5B0%5D%5BcomputeOn%5D=gf&indicators%5B0%5D%5Bparameters%5D%5Btimeperiod%5D=5&indicators%5B0%5D%5Bparameters%5D%5Bnbdevup%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bnbdevdn%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bmatype%5D=0&indicators%5B1%5D%5Btype%5D=alpha&indicators%5B1%5D%5BcomputeOn%5D=gf&indicators%5B1%5D%5Bparameters%5D%5Btimeperiod%5D=30
Which is decoded to the following:
var recursiveDecoded = decodeURIComponent( jQuery.param(body) );
console.log(recursiveDecoded);
meta[prune]=true&meta[returnFields][]=gf&meta[returnFields][]=gh&meta[returnFields][]=gh&meta[returnFields][]=rt&meta[orient]=split&indicators[0][type]=beta&indicators[0][computeOn]=gf&indicators[0][parameters][timeperiod]=5&indicators[0][parameters][nbdevup]=2&indicators[0][parameters][nbdevdn]=2&indicators[0][parameters][matype]=0&indicators[1][type]=alpha&indicators[1][computeOn]=gf&indicators[1][parameters][timeperiod]=30
If just using a serialized string result on the server leaves the string as the key in a key value pair:
"query": {
"{\"meta\":{\"prune\":true,\"returnFields\":[\"gf\",\"gh\",\"gh\",\"rt\"],\"orient\":\"split\"},\"indicators\":[{\"type\":\"beta\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":5,\"nbdevup\":2,\"nbdevdn\":2,\"matype\":0}},{\"type\":\"alpha\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":30}}]}": ""
},
My backend processing is done with Python. What modules exist to convert the above result to a dict resembling the original object?
Well, since we hashed it out in the comments, I'll post the answer here for posterity.
Use a combination of JSON.stringify on the JavaScript side to serialize your data structure and json.loads on the Python side to deserialize it. Pass the serialized structure as a query string parameter ("query" in your example) and then read the value from that query string parameter in Python. Huzzah!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Converting JS array UNIX date integers into JS Date objects

Is there a way to convert UNIX epoch integers (1402079444, etc) in an array into JavaScript Date objects (Date.UTC(2014, 9, 14), etc) using jQuery?
I'm trying to pass a large JSON array generated by PHP to Highmaps.JS, which almost works great however Highmaps expects a Date object and Date objects aren't valid JSON, so I can't generate them with PHP.
jsFiddle of my current setup here: http://jsfiddle.net/dwgLtscm/2/
(The x-axis isn't displaying dates properly because the data isn't in the proper date format).
[{
"name": "Dissolved Oxygen",
"data": [
[1402079444,9]
]
},
{
"name": "Temperature (Water)",
"data": [
[1401291099,9],
[1401862547,12]
]
},
{
"name": "Temperature (Air)",
"data": [
[1401291099,13],
[1401862547,19]
]
},
]
Given the Json object above, I'd try:
array.forEach(function (val) {
val.data = val.data.map(function (datum) {
return [ new Date(datum[0] * 1000), datum[1] ];
}
}
Unless I'm reading it wrong (I'm assuming data[0] is the UTC value).
(Edited based on feedback below, thanks all!)

Categories