How to Access the Nested Data in This Complex JSON, Which Includes Another JSON Document as One of the Strings

How can I access the nested data in this complex JSON, which includes another JSON document as one of the strings?

In a single line -

>>> json.loads(data['data']['video_info'][0]['announcement'])['content']
'FOLLOW ME PLEASE'

To help you understand how to access data (so you don't have to ask again), you'll need to stare at your data.

First, let's lay out your data nicely. You can either use json.dumps(data, indent=4), or you can use an online tool like JSONLint.com.

{
'data': {
'time': '1515580011',
'video_info': [{
'announcement': ( # ***
"""{
"announcement_id": "6",
"name": "INS\\u8d26\\u53f7",
"icon": "http:\\\\/\\\\/liveme.cms.ksmobile.net\\\\/live\\\\/announcement\\\\/2017-08-18_19:44:54\\\\/ins.png",
"icon_new": "http:\\\\/\\\\/liveme.cms.ksmobile.net\\\\/live\\\\/announcement\\\\/2017-10-20_22:24:38\\\\/4.png",
"videoid": "15154610218328614178",
"content": "FOLLOW ME PLEASE",
"x_coordinate": "0.22",
"y_coordinate": "0.23"
}"""),
'announcement_shop': ''
}]
},
'msg': '',
'status': '200'
}

*** Note that the data in the announcement key is actually more json data, which I've laid out on separate lines.

First, find out where your data resides. You're looking for the data in the content key, which is accessed by the announcement key, which is part of a dictionary inside a list of dicts, which can be accessed by the video_info key, which is in turn accessed by data.

So, in summary, "descend" the ladder that is "data" using the following "rungs" -

  1. data, a dictionary
  2. video_info, a list of dicts
  3. announcement, a dict in the first dict of the list of dicts
  4. content residing as part of json data.

First,

i = data['data']

Next,

j = i['video_info']

Next,

k = j[0] # since this is a list

If you only want the first element, this suffices. Otherwise, you'd need to iterate:

for k in j:
...

Next,

l = k['announcement']

Now, l is JSON data. Load it -

import json
m = json.loads(l)

Lastly,

content = m['content']

print(content)
'FOLLOW ME PLEASE'

This should hopefully serve as a guide should you have future queries of this nature.

How to access nested JSON data

To be honest, I can't understand your problem. JSON is already structured out, why do you need to change the structure?

In you case, I would access it as follows:

data.address.streetName;

If, by any chance, what you want is to traverse the data, you would need:

function traverse_it(obj){
for(var prop in obj){
if(typeof obj[prop]=='object'){
// object
traverse_it(obj[prop[i]]);
}else{
// something else
alert('The value of '+prop+' is '+obj[prop]+'.');
}
}
}

traverse_it(data);

Update

After reading below, what this user needs seems more obvious. Given property names as a string, s/he wants to access the object.

function findProp(obj, prop, defval){
if (typeof defval == 'undefined') defval = null;
prop = prop.split('.');
for (var i = 0; i < prop.length; i++) {
if(typeof obj[prop[i]] == 'undefined')
return defval;
obj = obj[prop[i]];
}
return obj;
}

var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
var props = 'address.streetName';
alert('The value of ' + props + ' is ' + findProp(data, props));

Python Accessing Nested JSON Data

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

How to get the value from a Nested JSON object from a JSON file using Typescript?

You could do something like this to get the key and value.

const printKeyAndValue = (objVal: any) => {
for (const key of Object.keys(objVal)){
console.log(key);
console.log(objVal[key]);
}
};

const obj = {
'item1': 123,
'item2': 'some string value'
};

printKeyAndValue(obj);

Please note the sample I have provided is an object with primitive types only and only top level properties. If you have a nested structure, you must handle accordingly.

How to access nested data using python

Here is the solution

data = {'data': ({'top_data': {'center': (-7, 1, 90), 'coord': 1}, 'id': 0, 'pos': (48, 205)}, {'top_data': {'center': (7, 10, 40), 'coord': 1.5}, 'id': 1, 'pos': (43, 105)}), 'centers_ob': {0: (19, 14, -20), 1: (-49, 22, 26)}, 'time': 13}
print(data['data'][0]['top_data'])
print(data['data'][1]['top_data'])
print(data['centers_ob'])
print(data['time'])

Though you should check nested dict

extract nested elements from json file using python

resp['fromRelationships']['manages'] is a list. You need to iterate over items in the list and get item['id']. You can use list comprehension like this:

hypervisorsName = [item.get('id')
for item in resp['fromRelationships']['manages']
if item.get('type') == 'HYPERVISOR']

How to get specific value from nested JSON object?

From the following class: JSONResponse

Not sure if you were using a library, or has a POJOs called JSONResponse

Also, you're calling the JSONResponse#getData, it means there's a getter called getData

presumably, your project already has a POJO for the attributes inside "data": [ { ... }, { ... } ] objects

E.g:

public class JSONResponse {
private List<Data> data;
private String success;

// getter & setter omitted
}

public class Data {

private Integer id;
private String nama;
private Integer harga;
private String deskripsi;
private Integer gambarid;
private Boolean paketan;
private String fasilitas;
private Integer totalTiket;
private Integer minTiket;
private String createdAt;
private String updatedAt;
private Object deletedAt;
private Integer gambarId;
private Gambar gambar;

// getter and setter omitted

}

public class Gambar {

private Integer id;
private String url;
private Object isGallery;
private String createdAt;
private String updatedAt;
private Object deletedAt;

// getter and setter omitted

}

Generate POJOs from JSON: https://www.jsonschema2pojo.org/

Or you can use plugins: https://plugins.jetbrains.com/plugin/8533-json2pojo

Here's the alternative approach might works for your usecases:

@override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response)
{
JSONResponse jsonResponse = response.body();
wisataList = new ArrayList<Data>();

Intent intent = getIntent();
int id = intent.getIntExtra(HomeActivity.EXTRA_NUMBER, 0);
for (int i = 0; i<jsonResponse.getData().length; i++)
{
Data wisata = jsonResponse.getData().get(i);
if (id == wisata.getId())
{
wisatList.add(wisata);
// break; // optional if you want to stop iterating, if the wisata already found
}
}
PutDataIntoRecyclerView(wisataList);

parsing complex json in nested object flutter

You can copy paste run full code below

You can see full code of related class below

code snippet

Record recordFromJson(String str) => Record.fromJson(json.decode(str));
...
Record record = recordFromJson(jsonString);
print(
'${record.trainingPlan.visuals[0].type} ${record.trainingPlan.visuals[0].value}');

output

I/flutter (30092): color red

full code

import 'package:flutter/material.dart';
import 'dart:convert';

Record recordFromJson(String str) => Record.fromJson(json.decode(str));

String recordToJson(Record data) => json.encode(data.toJson());

class Record {
String name;
String email;
String age;
String photo;
String url;
TrainingPlan trainingPlan;

Record({
this.name,
this.email,
this.age,
this.photo,
this.url,
this.trainingPlan,
});

factory Record.fromJson(Map<String, dynamic> json) => Record(
name: json["name"],
email: json["email"],
age: json["age"],
photo: json["photo"],
url: json["url"],
trainingPlan: TrainingPlan.fromJson(json["trainingPlan"]),
);

Map<String, dynamic> toJson() => {
"name": name,
"email": email,
"age": age,
"photo": photo,
"url": url,
"trainingPlan": trainingPlan.toJson(),
};
}

class TrainingPlan {
String id;
String creator;
String creationDate;
List<Visual> visuals;
Transition transition;
Duration duration;

TrainingPlan({
this.id,
this.creator,
this.creationDate,
this.visuals,
this.transition,
this.duration,
});

factory TrainingPlan.fromJson(Map<String, dynamic> json) => TrainingPlan(
id: json["id"],
creator: json["creator"],
creationDate: json["creationDate"],
visuals:
List<Visual>.from(json["visuals"].map((x) => Visual.fromJson(x))),
transition: Transition.fromJson(json["transition"]),
duration: Duration.fromJson(json["duration"]),
);

Map<String, dynamic> toJson() => {
"id": id,
"creator": creator,
"creationDate": creationDate,
"visuals": List<dynamic>.from(visuals.map((x) => x.toJson())),
"transition": transition.toJson(),
"duration": duration.toJson(),
};
}

class Duration {
String type;
String time;

Duration({
this.type,
this.time,
});

factory Duration.fromJson(Map<String, dynamic> json) => Duration(
type: json["type"],
time: json["time"],
);

Map<String, dynamic> toJson() => {
"type": type,
"time": time,
};
}

class Transition {
String length;
String delay;

Transition({
this.length,
this.delay,
});

factory Transition.fromJson(Map<String, dynamic> json) => Transition(
length: json["length"],
delay: json["delay"],
);

Map<String, dynamic> toJson() => {
"length": length,
"delay": delay,
};
}

class Visual {
String type;
String value;

Visual({
this.type,
this.value,
});

factory Visual.fromJson(Map<String, dynamic> json) => Visual(
type: json["type"],
value: json["value"],
);

Map<String, dynamic> toJson() => {
"type": type,
"value": value,
};
}

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
String jsonString = '''
{
"name": "Lionel Messi",
"email": "LionelMessi@gmail.com",
"age": "23",
"photo": "https://img.bleacherreport.net/img/images/photos/003/738/191/hi-res-bd496f7bef33e47363703d3cce58c50e_crop_north.jpg?h=533&w=800&q=70&crop_x=center&crop_y=top",
"url": "http://www.john-wesley.com",
"trainingPlan": {
"id": "1",
"creator": "LionelMessi@gmail.com",
"creationDate": "21/04/20",
"visuals": [
{
"type": "color",
"value": "red"
}
],
"transition": {"length": "2", "delay": "1"},
"duration": {"type": "Countdown", "time": "20"}
}
}
''';

Record record = recordFromJson(jsonString);
print(
'${record.trainingPlan.visuals[0].type} ${record.trainingPlan.visuals[0].value}');

setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}


Related Topics



Leave a reply



Submit