Json manipulation TypeScript Angular 2 - json

I come from a Python Background and recently started programming using TypeScript and Angular2. I want to know how to obtain keys from a JSON object using TypeScript.
I have a response like so:
response.text()
I pass this object to a function
removeMetaData (my_data: string){
//(Various manipulation)...etc
}
i have read that I can call a json() method instead of text(). If I do that, what is the type I should use for my_data?
Then,
If my JSON looks like this:
{
"count": 100,
"next_page": "http://www.test.com/users/?page=2",
"prev_page": "http://www.test.com/users/?page=3",
"results":[
{
"username": "johnny"
},
Etc....
]
How do I parse that?
I've read I might have to use an interface but I don't understand how.
In python it's just response["next_page"] to get the key of a dictionary, then I can assign that value to a variable within the class. That is exactly what I'm trying to achieve within a component.
Thank you.
ADDITION
list() {
this.requestService.get(this.api_path)
.subscribe(
response => this.populate(response.json()),
error => this.response = error.text()
)
}
populate(payload: object) {
this.count = payload.count;
this.next = payload.next;
this.previous = payload.previous;
*payload.results => this.users = payload.results;******
}

Declare an interface which will be used as value object.
export interface IPage
{
count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}
var my_data:IPage;
Now assign parsed json value to my_data and access all the properties with '.' operator i.e. my_data.count, my_data.results.
Feel free to throw any question.

If I do that, what is the type I should use for my_data?
Its just a javascript object.
As an example if you json looks like:
{
"foo": {
"bar": "bas"
}
}
Then in the parsed json (in variable someObj) the value someObj.foo.bar would be bas 🌹

Related

How to iterate through nested dynamic JSON file in Flutter

So I have two JSON files with different fields.
{
"password": { "length": 5, "reset": true},
}
"dataSettings": {
"enabled": true,
"algorithm": { "djikstra": true },
"country": { "states": {"USA": true, "Romania": false}}
}
I want to be able to use the same code to be able to print out all the nested fields and its values in the JSON.
I tried using a [JSON to Dart converter package](https://javiercbk.github.io/json_to_dart/.
However, it seems like using this would make it so I would have to hardcode all the values, since I would retrieve it by doing
item.dataSettings.country.states.USA
which is a hardcoded method of doing it. Instead I want a way to loop through all the nested values and print it out without having to write it out myself.
You can use ´dart:convert´ to convert the JSON string into an object of type Map<String, dynamic>:
import 'dart:convert';
final jsonData = "{'someKey' : 'someValue'}";
final parsedJson = jsonDecode(jsonData);
You can then iterate over this dict like any other:
parsedJson.forEach((key, value) {
// ... Do something with the key and value
));
For your use case of listing all keys and values, a recursive implementation might be most easy to implement:
void printMapContent(Map<String, dynamic> map) {
parsedJson.forEach((key, value) {
print("Key: $key");
if (value is String) {
print("Value: $value");
} else if (value is Map<String, dynamic>) {
// Recursive call
printMapContent(value);
}
));
}
But be aware that this type of recursive JSON parsing is generally not recommendable, because it is very unstructured and prone to errors. You should know what your data structure coming from the backend looks like and parse this data into well-structured objects.
There you can also perform input validation and verify the data is reasonable.
You can read up on the topic of "JSON parsing in dart", e.g. in this blog article.

How can I get a deep element of a json string in scala?

I am using Scala to parse json with a structure like this:
{
"root": {
"metadata": {
"name": "Farmer John",
"hasTractor": false
},
"plants": {
"corn": 137.137,
"soy": 0.45
},
"animals": {
"cow": 4,
"sheep": 12,
"pig": 1
}
}
}
And I am currently using the org.json library to parse it, like this:
val jsonObject = new JSONObject(jsonString) // Where jsonString is the above json tree
But when I run something like jsonObject.get("root.metadata.name") then I get the error:
JSONObject["root.metadata.name"] not found.
org.json.JSONException: JSONObject["root.metadata.name"] not found.
I suspect I can get the objects one at a time by splitting up that path, but that sounds tedious and I assume a better json library already exists. Is there a way to easily get the data the way I am trying to or is there a better library to use that works better with Scala?
The JSONObject you are using is deprecated. The deprecation message sends you to The Scala Library Index. I'll demonstrate how this can be done in play-json. Let's assume that the json above is stored at jsonString, so we can do:
val json = Json.parse(jsonString)
val path = JsPath \ "root" \ "metadata" \ "name"
path(json) match {
case Nil =>
??? // path does nont exist
case values =>
println(s"Values are: $values")
}
Code run at Scastie.
Looks like I was able to solve it using JsonPath like this:
val document = Configuration.defaultConfiguration().jsonProvider().parse(jsonString): Object
val value = JsonPath.read(document, "$.root.metadata.name"): Any

How to read a JSON object with a full-stop in the name using POSTMAN?

I have a problem trying to check a JSON value in the response body using POSTMAN because the JSON object name has a full-stop in it
Usually a JSON response body would be something like this:
{
"restapi": "Beta",
"logLevel": "INFO"
}
So normally we can do a test on the JSON value like this using POSTMAN:
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.restapi).to.eql(Beta);
});
But the problem I'm having now is that the JSON object name has a full stop like this
{
"restapi.name": "Beta",
"logLevel.sleep": "INFO"
}
So if I try to do read the object like this, it will come out with an error
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.restapi.name).to.eql(Beta);
});
You can just reference the key value by using brackets around the name:
jsonData["restapi.name"]
object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]
this should do the trick
jsonData["restapi.name"]

How to get a key value in a json object and affect it into the same object?

I have a json object with some keys and values.
I would like to get a generic way to get one of these values and set (into the same object) a variable with this value.
myObj = {
"name":"John",
"age":30,
"cars": {
"key":"John",
"car2":"BMW",
"car3":"Fiat"
}
}
myObj = {
"name":"John",
"age":30,
"cars": {
"other-name":"John",
"car2":"BMW",
"car3":"Fiat"
}
}
You can use either object.property.anotherProperty form, or object["property"]["anotherProperty"] access form to read and to set value, for example:
myObj.cars.car2 = myObj.cars.car3;
P.S. assuming Javascript
You can assign new value as follow.
myObj.cars.newKey = "Any Value"
That's some nice answer but I would like to know when im writting inside the jsonfile on vi

How to change Process[Task, ByteVector] to json object?

I use http4s and scalaz.steam._
def usersService = HttpService{
case req # POST -> Root / "check" / IntVar(userId) =>{
//val jsonobj=parse(req.as[String])
val taskAsJson:String = write[req.body]
Ok(read[Task](taskAsJson))
}
}
For http4s, the request can get body as the type Process[Task, ByteVector]
The Process is scalaz.stream.process class. You can find details on scalaz.
I want to write a Task here can deal with JSON ByteVector and translate into a Map (like HashMap), layer by layer.
I mean, for example:
{
"id":"12589",
"customers":[{
"id": "898970",
"name":"Frank"
...
},
]
}
I do not know how to write the function via scalaz.stream.Process to change the JSON to mapobject.
I want response and to parse the JSON object, returning another refactored JSON object; how can I do it?