Output json stringify elements - json

I have a problem. I am using TypeScript and I get a response back. I want to output the information. How could I output e.g. internalCompanyCode and timestamp.
What I got
Element implicitly has an 'any' type because index expression is not of type 'number'.(
//const json = JSON.stringify(result, null, 2)
// json is the result of JSON.stringify(...)
const json = [
{
"internalCompanyCode": "007",
"moreInfo": [
{
"dimensions": {
"height": 27,
"width": 31,
"length": 61
},
"currenStatus": {
"arrived": {
"timestamp": "10:00:12"
}
}
}
]
}
]
console.log(json['internalCompanyCode'])
console.log(json['moreInfo']['dimensions']['height'])

To get data you don't have to stringify result. You have to use result before stringifying to json or have to parse json back to result if you did it
console.log(result[0]['internalCompanyCode']) //007
console.log(result[0]['moreInfo'][0]['currenStatus']['arrived']['timestamp']) // 10:00:12
console.log(result[0]['moreInfo'][0]['dimensions']['height']) //27

Your json object is actually a list so you will have to access it like json[0]['internalCompanyCode']

Related

Add string literal into JSONPath output

Can I add a string literal to a JSONPath selector?
{ "items": [
{ "x": 1 },
{ "x": 2 },
{ "x": 3 },
{ "x": 4 }]
}
$.items[:].x gives...
[
1,
2,
3,
4
]
For example, can I make it return...
[
{ 1 },
{ 2 },
{ 3 },
{ 4 }
]
I want to generate some code that adds items to a dictionary.
As discussed in the comments, this cannot be done using JSONPath (alone) since a path query returns only valid JSON and the target format is not valid. In general, JSONPath is not the right tool here, a JSON transformation using a library like Jolt would be more appropriate; but again, similar to XSLT transformations, we can only create valid output. So, as you already have found out, you would need to use string functions to mingle the code as needed. For instance, a regex substitution could do:
const regex = /(\d+),?/gm;
const str = `[
1,
2,
3,
4
]`;
const subst = `{ $1 },`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

Ruby: Parsing Json statements that use x[{a:b, c:d}]

I'm parsing a JSON document like
{
"status": "ok",
"tick": {
"id": 101006380508,
"data": [
{
"id": "10100638050832281590023",
"amount": 0.2251,
}
]
}
}
I am currently doing:
data = JSON.parse(response.read_body)
data["tick"]["data"]["amount"]
and getting an error
Error: []': no implicit conversion of String into Integer (TypeError)
My objective is the get the amount
It's array that contains one hash, so you can get it as
data["tick"]["data"].first["amount"] # => 0.2251

How to parse JSON data with custom object names?

I want to parse a JSON with Typescript, where object names can vary and I have no way to know them all. For example:
{
"planets": {
"Alderaan": {
"available_items": {
"Cinamone": {
"available": 74,
"buy_price": 6,
"sell_price": 6
},
"Dwimeryt": {
"available": 42,
"buy_price": 12,
"sell_price": 11
}
}
}
}
Where there can be many planets with different names.
I figured out that in order to parse JSON object successfully, we need to have corrent variable names, so for example that works:
interface MyObj {
x: number;
y: number:
}
let json_string = `{
"x": 5,
"y": 12
}`;
let test: MyObj = JSON.parse(json_string);
But if we change variable name in interface from "x" to lets say "xx" it becomes undefined after parsing. That creates seemingly unsolvable problem if we cant know all of the JSON object names, because I cant create an interface withh all of the planet names. Am I missing something? How would you parse a JSON I have posted?
Do you have any influence on the JSON itself? To me it seems that it is not the best way to use JSON. If I would try to design this, your JSON would look more like this:
{
"planets": [
{
"name": "Alderaan",
"available_items": [
{
"name": "Cinamone",
"available": 74,
"buy_price": 6,
"sell_price": 6
}, {
"name": "Dwimeryt",
"available": 42,
"buy_price": 12,
"sell_price": 11
}]
}]
}
This way you would always know the name of the fields and also their types. I do not think that this could be achieved easily with the current JSON format.

Json object with nested objects, nested objects | mockable

I'm trying to create a test API in mockable.
What am I trying to create?
I'm trying to build an Json object with a Nested object which holds another nested object.
Example for use: store object => Store info => product list
What I expect to create
{
"Object": {
"id": 0,
"name": "Nova",
"nestedObject": {
{
"id": 1,
"name": "NestedNestedObject1",
},
{
"id": 2,
"name": "NestedNestedObject2",
},
}
Result I'm getting:
Error: Parse error on line 11:
...: { {
----------------------^
Expecting 'STRING', '}'
At NestedNestedObject2
How do I create a nested, nested object? If I'm correct mockable accepts pure Json
It depends on what you want to create and that depends on your API. The actual problem is that your JSON is not valid.
After your nestedObject there is just a { and that is wrong. In this case I assume you want to have an array of nestedObject (and perhaps also name should be nestedObjects) so fix would be (see the array []):
{
"Object": {
"id": 0,
"name": "Nova",
"nestedObject": [
{
"id": 1,
"name": "NestedNestedObject1"
},
{
"id": 2,
"name": "NestedNestedObject2"
}
]
}
}

I need to get the primitive data type from json path using in-definite path

Given this document:
{
"slide": [{
"title": {
"fontName": "Open Sans",
"top": 188,
"left": -22,
"width": 597,
"fontSize": 45,
"valign": "bottom",
"presetType": "Parallelogram",
"fill": "#6bcad5",
"halign": "left",
"fontColor": "#f4dde6",
"height": 192
}
}, {
"picture": {
"top": 25,
"left": 54,
"width": 1,
"colorMode": "GRAYSCALE",
"presetType": "Snip_Same_Side_Rect",
"height": 1
}
}]
}
The following code returns [54]:
JSONArray obj = ctx.read("$.slide[?(#.picture)].picture.left");
But I need a primitive type, still maintaining the indefinite path.
According to the docs:
Please note, that the return value of jsonPath is an array, which is also a valid JSON structure. So you might want to apply jsonPath to the resulting structure again or use one of your favorite array methods as sort with it.
Note: if you are using the Java implementation then an issue has already been raised for this and the response to that issue reiterated the above point.
So, as long as you use a filter you'll need two calls, for example:
String json = "...";
DocumentContext ctx = JsonPath.parse(json);
// capture the JSONArray
JSONArray obj = ctx.read("$.slide[?(#.picture)].picture.left");
// read the first value from the JSONArray
// prints "54"
System.out.println(obj.get(0));
// alternatively, push the JSON representation of the JSONArray back through JsonPath
Integer value = JsonPath.read(obj.toJSONString(), "$[0]");
// prints 54
System.out.println(value);