I am doing a get request on JS and with the json reponse i want to get some values, for example product and color, but i don't know how i can go more deeper on the next levels of the objects of the Json.
the Json:
{
"items": {
"1man": {
"312favorites": {
"155description": {
"color": "red",
"price": 2.76666
}
}
}
}
}
I just can go until the 1man level i don't know how to get the next levels, my code until now
console.log(response.data.items['1man']);
If i try for example console.log(response.data.items['1man'].312favorites i get error on VScode, i want go to until the color value...
Does someone can help me here?
You have to do it this way:
response.data.items['1man']['312favorites']['155description'].color
The reason is that the key has some numbers, and it can't be accessed with Dot notation because it has to be without any numbers or special characters that's why you must use Bracket notation .
I am currently making an ajax call to return data from an API. The return value is an object of an array. This format is an invalid object so I am having issues accessing the data that is being returned to me.
How can I convert this object into a valid json object so I can access the data that is being returned?
Here is an example of the data being returned:
data = { ["<p>Retail Websites has a profit value of $243,291. In the year 2020 we have seen a growth rate of about 2.3% </p>" ] }
I've tried using dataType: json in my ajax call but the result value is still the same.
Here is my ajax call using "dataType: json" :
$.ajax({
type: "POST",
url: dataUrl,
data: {
"retailId": retailId,
},
dataType: "json",
async: true,
error: function () {
console.log("error")
}
}).done(function (data) {
console.log("retail data", data)
})
I am unable to access the data in this object. I am expecting to be able to access the data like a json object such as : data[0]. I am stuck on how to accomplish this.
If your data is set as:
var data = { ["<p>Retail Websites has a profit value of $243,291. In the year 2020 we have seen a growth rate of about 2.3% </p>" ] }
Then the problem is the curly braces with no key. When you remove them, the array is correct. data[0] is equal to the string you expect.
If the result of your API call is the whole of data = {...} and you know that it is, then you can capture the string, remove the characters at the beginning and end that don't belong (everything outside the square brackets) and use JSON.parse to get your JSON data. There are several ways to remove the characters. If the text is always the case, you can use substrings, or if you need to be more flexible, you can use regular expressions.
My JSON is like below
{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}
{"_id":1270260,"name":"State of Haryāna","country":"IN","coord":{"lon":76,"lat":29}}
{"_id":708546,"name":"Holubynka","country":"UA","coord":{"lon":33.900002,"lat":44.599998}}
It is a JSON without comma separation, how to read this file? I tried to parse the JSON and add commas in between, but couldn't do that either.
myapp.controller('Ctrl', ['$scope', '$http', function($scope, $http) {
$http.get('todos.json').success(function(data) {
var nuarr = data.toString().split("\n");
for(i in nuarr) {
myjson.push(i+",");
}
});
}]);
This format is typically called "newline-delimited JSON" or "ndjson"; there are several modules that can parse this, but if you're data set is small and you can do it all at once, you're on the right track:
var ndjson = "..." // assuming your data is already loaded in as a string
var records = ndjson.split('\n').map(function (record) {
return JSON.parse(record)
})
That simplifies it a bit, but then you have all of your records in an array, as parsed JSON objects. What you do to them after that is up to you, but the key takeaway here is that your JSON is a list of objects, not a single object: you don't want to parse it as a whole, but as individual records.
Say then, you want to create an object whose keys are the individual IDs; that might be helpful:
var recordHash = {}
records.forEach(function (record) {
recordHash[record._id] = record
})
Now you can address the individual records as recordHash['12345678'] assuming that 12345678 is the id of the record you wanted. You'll want to mutate the records into whatever data structure makes sense for your application, so it really depends on what you're looking for, but that example might get you started.
I really don't recommend trying to mutate the data that you're receiving into some other format before parsing; it's fragile. You'll find it much safer and more re-usable to parse out the data in the way you were provided it, and then transform it into whatever data structure makes sense for your application.
$http.get expects that response must be json. You can write your own custom response transformer to do that so.
$http({
url: 'todos.json',
method: 'GET',
transformResponse: function (data) {
return data.split('\n').map(function(line) {
return JSON.parse(line);
});
}
}).success(function (response) {
console.log(response);
// do whatever you want to do
// response will be of type array of objects
});
Your JSON needs to be a single object or array. Just joining a bunch of objects together with a comma does not define a single JSON object. Try this instead to get a parsable array of objects:
var nuarr = data.toString().split("\n");
myjson = '[' + nuarr.join(',') + ']';
Then JSON.parse(myjson) should return an array of objects. Alternatively, you can just map each element of nuarr to it's JSON-parsed value and collect the results in another array.
$http.get expects that response must be json. You can write your own custom response transformer to do that so.
$http({
url: 'todos.json',
method: 'GET',
transformResponse: function (data) {
return data.split('\n').map(function(line) {
return JSON.parse(line);
});
}
}).success(function (response) {
console.log(response);
// do whatever you want to do
// response will be of type array of objects
});
var myJson = nuarr.join(',');
But what are you really trying to do? Your code is pushing the strings with a comma added into an array, so end up with
["{...},", "{...},", ...]
As I see it, You have a collection of json objects, with the delimiter as newline.
Try this:
myapp.controller('Ctrl', ['$scope', '$http', function($scope, $http) {
$http.get('todos.json').success(function(data) {
myjson = data.split("\n").map(function(line) { return JSON.parse(line); });
});
}]);
Use a regexp to split into lines, then map each line into its JSON-parsed equivalent, yielding an array of the objects on each line:
input . match(/^.*$/gm) . map(JSON.parse)
Or use split as other answers suggest:
input . split('\n') . map(JSON.parse)
As stupid as it may seem, we got tired of using commas and quotes with JSON, along with not having comments or multiline strings.
Knowing that Douglas Crockford and his disciples would cry 'Blasphemy', we proceeded to write a specification, parser, and formatter for our own Relaxed Json syntax.
The fact is you don't really need commas, and quotes are only needed in a few exceptional cases. And you don't need newlines either.
With Relaxed Json, to make your example work, you would just put '[' and ']' around what you already have and call
val realJson = parser.stringToJson(...)
But you don't need newlines between the array values.
And you can also remove all the commas in-between your key-values.
And you don't need quotes around your keys.
So you could do this:
[
{ _id:707860 name:Hurzuf country:UA
coord:{lon:34.283333 lat:44.549999}
}
{ _id:519188 name:Novinki country:RU
coord:{lon:37.666668 lat:55.683334}
}
]
Link To Specification:
http://www.relaxedjson.org
Link To NPM
https://www.npmjs.com/package/really-relaxed-json
Paste the example here to see how easy it is to parse:
http://www.relaxedjson.org/docs/converter.html
Update 2022
#milkandtang answer put me on the right path but JSON.parse() gave me trouble and returned errors even after splitting the lines. It keeps complaining about lines being empty or malformated.
This is what works for me with New-Line Delimited JSON
var ndjson = data;//must be a string
//declare variable that will be array of json
var json = [];
//split
ndjson.split('\n').map(function (record) {
//regex to format each array to a json object
var array = JSON.parse(`[${record.replace(/\}\n\{/g, '},{')}]`);
//push to json array
json.push(array);
})
//pheeew...
console.log(json);
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\" }]"
I've found that I can't use the standard JSON string in the Cypher query while I were writing a Node.js application:
var neo4j = require('neo4j')
,db = new neo4j.GraphDatabase('http://localhost:7474')
,enc_datum = JSON.stringify({id: 1, data: 'foo'})
,qstr = ['MATCH (n %DATUM)'
,'RETURN n'
].join('\n')
.replace('%DATUM', enc_datum)
db.query(qstr)
It would complain about the '"' character, because Cypher accept encoded object like this:
MATCH (n {id: 1, data: 'foo'})
RETURN n
Which is not what encoded with JSON:
var enc_datum = JSON.stringify({id: 1, data: 'foo'})
console.log(enc_datum)
// would be {"id":1,"data":"foo"}
The error messages show that Cypher, or the Neo4j module, doesn't accpet standard JSON because of the " character. It would complain that the next character after the { should be identifier or something else.
So I got stuck: either I must handle the JSON string with some nasty RegExpr before it got embedded in the query string, or I must invent a way to encode objects just for the tiny " character. I just want to ask if there're some more suitable solutions before I jump into these two tricky ways...
(I now solve this in test by using eval instead of JSON to eval my encoded data, while the string would be directly used in the Cypher query so I can't use JSON to stringify it. But I can't handle client encoded JSON in this way)
MATCH (n {id: 1, data: 'foo'})
The format you seem to be using is JSON5. You can avoid double quotes with code like this:
var jju = require('jju')
jju.stringify({id: 1, data: 'foo'}, {quote:"'"}).replace(/"/g,'\\x22')
// result: "{id: 1, data: 'foo'}" (string)
jju.parse("{id: 1, data: 'foo'}")
// result: {id: 1, data: 'foo'} (object)
Please note two important things here:
"quote" parameter ensures that module will always use single quotes to wrap strings
replace() ensures that all double quotes will be encoded as \x22 if they happen to be in your input (i.e. data: 'foo"bar')
I don't know what other restrictions do that database have, maybe it's worth to encode it with base64 or something.
Cypher doesn't use JSON it is a map format that looks a bit like JSON but doesn't use quotes for keys
use parameters instead MATCH (n {props}) pass the actual parameters as values
like this
{"query","MATCH (n {props}) return n",
"params": {"props":{"id":1,"data":"foo"}}}