I am trying to parse in this result of data which i obtained from xml conversion to json parsing :
var output = [{"SearchResults:searchresults":{"$":{"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation":"someurl","xmlns:SearchResults":"someurl"},"request":[{"keyval":["keydata"]",...}]}]}]}]}]}]}}]
How to get keydata of keyval. I tried parsing and stringify also but no results.
Thanks in Advance
Your unreadable comment does not really shed much light on the issue. My guess is that you retrieve JSON though AJAX with jQuery, thus your JSON is already decoded when you display it in the console (that's what jQuery is good at) and you no longer have a JSON string but good old JavaScript array. Your question is probably the classical "how do I read a deeply nested piece of data" we see a lot here.
Using proper indentation everything's cleaner:
var output = [
{
"SearchResults:searchresults": {
"$": {
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "someurl",
"xmlns:SearchResults": "someurl"
},
"request": [
{
"keyval": [
"keydata"
]",
...
First item of array:
output[0]
First key:
output[0]["SearchResults:searchresults"]
Next level:
output[0]["SearchResults:searchresults"]["$"]
... etc.
Related
What is the best practice to pass an array of objects throught query string in REST style?
For example, the array:
examples[] = [
{
name: "foo",
value: "1"
},
{
name: "bar",
value: "2"
}
]
I thought about it:
/items?examples[0][name]=foo&examples[0][value]=1&examples[1}[name]=bar&examples[1][value]=2
Are there other ways to do this?
Upd:
I need readable URL to show it to the user in the address field. It should display state of some filters in the table, I'm not sending it to the backend.
Since you're parsing this manually in JS, you could keep the structure you have and just write a parsing function
var items = {};
location.search.split("?")[1].split("&").map((q) => {
var [token, value] = q.split("="),
[idx, key] = /\[([0-9+])\]\[(\w+)\]/g.exec(token).slice(1, 3);
if (!items[idx]){
items[idx] = {};
}
items[idx][key] = value;
})
This will yield you something with a structure like
{
"0": {
"key1": "data"
"key2": "data:
},
"1": {
"key1": "data"
"key2": "data"
}
}
If you need it to end up an array, it would be pretty easy to convert, but keeping it as an object with numeric strings for keys will prevent an error if it's not sequential.
Also, note there's no error checking or anything here, so if you're going to have query string params that aren't in that format, you'll want to test for that and handle them differently.
You shouldn't take care about how pass data for a backend, Angular do it for you.
About your example, you probably want to update or save several item. So it's not into the url that you will pass your data but into the Request Body :
this.httpService.post(yourUrl, examples, yourHttpOptions).subscribe( (response) => {
// you manage your response data
});
REST does not care how you encode information into your identifiers. You can use any scheme you want, so long as it is consistent with the production rules defined by RFC 3986.
REST cares a little bit about how you share information about creating URI, in the sense that that information should be shared in some readily standardizable form, like an HTML form, or a URI Template.
We don't, to my knowledge, have a "readily standardizable form" that describes how to transform a json array to a query string.
But... REST does allow code on demand; embedding, for example, a bunch of java script into a resource where that javascript knows how to encode the json into the URI... that is in bounds, so long as you have the code on demand itself referenced in a readily standardizable way (like we have with HTML and script tags).
In practice? urlencode the json representation and put it onto the query string directly. That will get you through until you start to discover the real requirements that your URI design needs to support (requirements like: operators needing to be able to understand the access logs).
I am running a Javascript function on the latest version of Mozilla which receives a string which I want to convert to a JSON object. The conversion seems to be failing.
The string is being generated on the server side in a Java function:
result = "[{ \"userID\": 1 \"firstName\":\"John\" \"lastName\":\"Sheridan\" }{ \"userID\": 2 \"firstName\":\"Michael\" \"lastName\":\"Geribaldi\" }]";
(note that I am attempting to return an array of values for a list).
The code on the client side is the ajax callback shown below:
var successFunc = function(data, textStatus, jqXHR)
{
alert("Data: "+data);
var obj = $.parseJSON(data);
alert("Object: "+obj);
}
Apparently, the data is coming back to the callback and is being displayed in its string form, but the JSON parser is failing because the second alert is failing to appear. I am sure something is wrong with my string but am having trouble figuring out what. The debugger is not telling me anything, I am just seeing a silent failure.
I have also attempted this using the JSON.parser() function. I am seeing the same thing. I am making a mistake somewhere. Can someone tell me where?
Your json is not valid, you are missing comma
In order to parse your json should be like this
[
{ "userID": 1, "firstName":"John", "lastName":"Sheridan" },
{ "userID": 2, "firstName":"Michael", "lastName":"Geribaldi" }
]
JSON is a format where data is in key:value pairs separeted by , and key and value are enclosed in double quotes, where objects are enclosed in {} braces and array is enclosed in [] hope you have got the your mistake that where your json is lacking.
"[{
\"userID\": 1 ,
\"firstName\":\"John\",
\"lastName\":\"Sheridan\",
},
{
\"userID\": 2 ,
\"firstName\":\"Michael\",
\"lastName\":\"Geribaldi\" }]"
Folks,
Trying to understand returning and forming JSON responses.
The following code returns the object as a single string:
res.send(JSON.stringify(data));
Output to the browser:
{"Count":1,"Items":[{"dbsource":{"S":"x"},"number":{"S":"5002820"},"name":{"S":"blah,foo"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}
Dont I want the JSON output to be more readable, ie :
{
"one": "two",
"key": "value"
}
What should i change JSON.stringify(data) to? Ideally I want the response to be used as an API endpoint.
Thanks!
You are almost there. Use stringify with spaces
var str = JSON.stringify(data, undefined, 2);
The above string will have indentation with 2 spaces.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I'm looking at a json that looks like this
{
"key": "cow",
"value": "woof"
}
{
"key": "dog",
"value": "moo"
}
And i wan to parse it, but JSON.parse doesn't work because the thing as a whole isn't really json. There actually aren't any newlines either, so it looks like
{"key": "cow","value": "woof"}{"key": "dog","value": "moo"}
As to the why, this is the stream coming from a Comet endpoint. Ideally it should come one by one, but sometimes there's an interruption, and after it comes back i receive the list of all changes that have happened since the interruption happened, strung together. So if three dicts were meant to have come down while the connection was broken, i'll get them all at once at the end:
{"key": "cow","value": "woof"}{"key": "dog","value": "moo"}{"key":"cat","value":"baaa"}
Is there any convenient way of parsing this kind of json in the browser?
EDIT: Sorry guys, i didn't mention that the objects can be arbitrarily nested and can contain all sorts of things, Unicode characters, arrays, objects, arrays with objects, braces of all shapes and sizes, etc. etc. so most hacky string-split or regex solutions will fail in these cases. I didn't put any of these in the examples because i was being lazy, but a more representative example may be
{
"key": "cow",
"value": {
"body": "big",
"name": "sally",
"children": [
"bob",
"daisy"
]
},
"alt-key": "牛"
}
{
"key": "dog",
"value": "moo{}{}{}}}} i love brackets[[[]] ]]]] }{}",
"array": [
"豆沙包",
"叉烧包"
]
}
Although a regex/stringsplit thing would work 95% of the time, I'm looking for a strictly correct solution that'll always work when fed correct json
If values and keys won't contain }{, you could simply add commas to make it valid JSON (and add square brackets to make it an array):
var json = '[' + json.replace(/}{/g, '},{') + ']';
This would even work if you only get a single object as response.
Try like this:
var arrayOfObjects = flowstring.match(/{.*?}/g).map(function(value){
return JSON.parse(value);
});
and you will have this array of objects:
[{"key": "cow","value": "woof"},{"key": "dog","value": "moo"}.......]
If it were me, I'd just write a JSON parser that understands a stream of JSON expressions. JSON is about as easy to parse as grammars get, and making a parser that's able to "reset" itself for a new sentence is a simple (once the parser exists).
Heck you could start from the json.org parser itself.
To reliably "fix" your current data is a project that comes really close to writing a parser anyway.
Try converting that to an array, then parse that. Something like this:
var json = '{"key": "cow","value": "woof"}{"key": "dog","value": "moo"}';
var newjson = '[' + json.replace(/\}\{/g, '},{') + ']';
var obj = JSON.parse(newjson);
I have encountered a bizarre case when attempting to parse some JSON data sent from a server.
The data is essentially, a set of rows of data - i.e. a list of lists, and looks something like this:
[[1,2,3],[4,5,6],[7,8,9]]
In FF (using Firebug), the received JSON data is valid, and renders correctly.
When I attempt to parse the JSON data using either of this statements, it fails:
JSON.parse()
code breaks on error
jQuery.parseJSON()
parses without complaining, yet the result of the parse is a null object
The only way I have managed to successfully parse the JSON response, is to use the dreaded eval() statements, which is a BIG security issue.
Anyone knows what may be going on?
I'm just starting my adventure with JavaScript and JSON, but it looks like it's not a valid JSON object. There is no key:value in this list of lists. I wold suggest changing it into list of obects containing list fields. Sth like:
[
{ list: [ 1, 2, 3 ] },
{ list: [ 1, 2, 3 ] },
{ list: [ 1, 2, 3 ] }
]
But I might be very wrong.